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