What is the proper syntax for a method that checks a string for a pattern, and returns true or false if the regex matches?
Basic idea:
def has_regex?(str
In the question you said:
... method that checks a string for a pattern, and returns true or false if the regex matches
As johannes pointed out String=~ returns nil
if the pattern did not match and the position in the string where the matched word stared otherwise. Further he states in Ruby everything except nil
and false
behave like true
. All of this is right.
However, they are not exactly true
or false
. Therefore, the last step is to coerce the value to be a Boolean
. This is achieved by wrapping the result in double bangs returns a true
.
def has_regex?(string)
!!(string =~ /something/i)
end
Adding this to the String class makes it pretty simple to use:
class String
def match?(regex)
!!self.match(regex)
end
end
I added it to Rails initializer (RAILS_ROOT/config/initializers) and you can call directly from the string:
"Something special!".match?(/something/i) #=> true
"Somethin' special!".match?(/something/i) #=> false
If you are using Ruby 2.4 or later, there are String#match?(regex)
and Regexp#match?(string)
methods that return booleans without the conversion shenanigans (where needed, usually not), and have improved performance to boot.
https://ruby-doc.org/core-2.4.0/Regexp.html#method-i-match-3F
https://blog.cognitohq.com/new-features-in-ruby-2-4/
I do not have enough reputation to comment, so I will answer instead.
Use of ===, as suggested by viljar, is advised against in the Ruby Style Guide and will cause Rubocop complaints (under default rules).
I find the most readable way to be:
def match?(string)
!(string =~ /something/i).nil?
end