Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean check if a string matches a regex in ruby?

Tags:

regex

ruby

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
like image 748
kddeisz Avatar asked Dec 15 '22 02:12

kddeisz


2 Answers

You can use this:

def test(s)
    /Macintosh/ === s
end
like image 142
Casimir et Hippolyte Avatar answered Dec 29 '22 02:12

Casimir et Hippolyte


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

like image 37
Darren Weber Avatar answered Dec 29 '22 02:12

Darren Weber