Ruby: What's the proper syntax for a boolean regex method?

Viewed 19873

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?(string)
    pattern = /something/i
    return string =~ pattern
end

Use case:

if has_regex?("something")
    # woohoo
else
    # nothing found: panic!
end
10 Answers

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

For Ruby >= 2.4 or Rails, you can do:

 regexp.match?(string)

I do not have enough reputation to comment, so I will answer instead.

Use of ===, as suggested by viljar, is advised against in the Ruby Style Guide and will cause Rubocop complaints (under default rules).

I find the most readable way to be:

def match?(string)
  !(string =~ /something/i).nil?
end

If you want the put the pattern in a method, you can just do

def has_my_pattern(st)
    st =~ /pattern/
end

Or, perhaps better, put the pattern in a class variable instead?

Related