views:

59

answers:

4

I'm thinking there has got to be a cleaner way to check if a regular expression is not nil / is true. This is what I have been using: hold = (h4.text =~ /Blah/) if !hold.nil? ... end

I tried: !(h4.text =~ /Blah/).nil? but it did not seem to work.

+2  A: 

You can use unless here:

unless h4.text =~ /Blah/
  #...
end
Priit
+2  A: 
if h4.text !~ /Blah/
   # ...
end
kejadlen
A: 

Neither of the above seemed to work, this is what I ended up with:

unless (h4.text =~ /Blah/) == nil
   ...
end
TenJack
Why can't you just do `if h4.text =~ /Blah/`, if that's what you're looking for?
kejadlen
A: 
#!/usr/bin/ruby1.8

text = 'Blah blah blah'
puts "blah" if text =~ /Blah/    # => blah

text = 'Foo bar baz'
puts "blah" if text =~ /Blah/    # (nothing printed)
  • In a Ruby conditional statement, anything that is neither nil nor false is considered to be true.

  • =~ returns nil for no match, or an integer character position if there is a match.

  • nil is as good a false; an integer is as good as true.

Therefore, you can use the result of =~ directly in an if, while, etc.

Wayne Conrad