In ruby, I have seen a lot of code doing things like:
def test(s)
s =~ /Macintosh/
end
to test whether or not a string matches a regex. However, this returns a fixnum or nil, depending on if it finds a match. Is there a way to do the same operation, but have it return a boolean as to whether or not it matched?
The two possible solutions that I thought of were !(s =~ /Macintosh/).nil?
and !(s !~ /Macintosh/)
, but neither of those seem very readable. Is there something like:
def test(s)
s.matches?(/Macintosh/)
end
You can use this:
def test(s)
/Macintosh/ === s
end
Ternary syntax might help or fit a different style preference:
x = '10.0.0'
x =~ /\d*\.\d*\.\d*/ ? true : false # => true
# Unlike c-style languages, 0 is true in ruby:
x =~ /\d*\.\d*\.\d*/ # => 0
0 ? true : false # => true
The order of the case compare operator ===
is important [1], e.g.:
/\d*\.\d*\.\d*/ === x
#=> true
x === /\d*\.\d*\.\d*/
#=> false
[1] https://ruby-doc.org/core-2.2.0/Regexp.html#method-i-3D-3D-3D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With