Ruby: What's the proper syntax for a boolean regex method?
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
Your code looks fine, but you could write it even smaller.
The return value of String#=~
behaves this way:
nil
if the pattern did not match- the position in the string where the matched word started
In Ruby everything except nil
and false
behaves like true
in a conditional statement so you can just write
if string=~ pattern
# do something
else
# panic
end
To make it return true/false switch the position of pattern and string and use case equality ===
def has_regex?(string)
pattern = /something/i
return pattern === string
end
I absolutely needed it to return true boolean value and digged around. It is actually documented in regexp class http://www.ruby-doc.org/core-2.1.3/Regexp.html#method-i-3D-3D-3D