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? ...开发者_如何学Python end
I tried: !(h4.text =~ /Blah/).nil? but it did not seem to work.
You can use unless
here:
unless h4.text =~ /Blah/
#...
end
if h4.text !~ /Blah/
# ...
end
#!/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.
Neither of the above seemed to work, this is what I ended up with:
unless (h4.text =~ /Blah/) == nil
...
end
精彩评论