4

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
4
  • 2
    What about !!(string =~ /some regex/)? Commented Jan 28, 2014 at 21:34
  • 1
    @rathrio that would check and then check for nil, I'm asking if there's a boolean method that would return true or false. Commented Jan 28, 2014 at 21:38
  • Just out of interest: Is there a specific reason why you want a Boolean? In most use cases returning nil or a non-nil value would work just fine, right? Commented Jan 28, 2014 at 21:47
  • @rathrio The problem is, if the needle is at position 0 in the haystack, =~ returns 0. And while ruby evaluates 0 as true, mysql doesn't. It's a rails thing. Commented Jan 28, 2014 at 21:55

3 Answers 3

11

You can use this:

def test(s)
    /Macintosh/ === s
end
Sign up to request clarification or add additional context in comments.

4 Comments

The question is whether or not there exists a method that does a boolean check, without needing to check nil at the end. !! is the same as .nil?.
@kdeisz: where is the gift basket?
I am having a rubocop error for this... Avoid the use of the case equality operator(===). How can i use match method instead === ?
BTW, it's good style to add a ? to a boolean method, as in test?(s).
1

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

Comments

0

Since Ruby 2.4.0, you can use Regexp#match which returns a boolean result;

/Macintosh/.match?(s)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.