开发者

Refactoring a regular expression check in ruby

开发者 https://www.devze.com 2022-12-15 06:30 出处:网络
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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号