145

In ruby, I read some of the operators, but I couldn't find =~. What is =~ for, or what does it mean? The program that I saw has

regexs = (/\d+/)
a = somestring
if a =~ regexs

I think it was comparing if somestring equal to digits but, is there any other usage, and what is the proper definition of the =~ operator?

2
  • 2
    If you want to play around with Ruby regular expression I can recommend rubular.com Commented Apr 25, 2011 at 18:08
  • 7
    Can we mark the other question as a duplicate, rather than this one? This one has more votes, in terms of both the question itself and the answers. Also, searching for ruby =~ operator, this question is the first relevant hit in Google, Yahoo, Bing, and DuckDuckGo in my tests, which also explains why this one has more votes.
    – ryenus
    Commented Oct 24, 2014 at 5:07

3 Answers 3

206

The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.

/mi/ =~ "hi mike" # => 3 
"hi mike" =~ /mi/ # => 3 

"mike" =~ /ruby/ # => nil 

You can place the string/regex on either side of the operator as you can see above.

50

This operator matches strings against regular expressions.

s = 'how now brown cow'

s =~ /cow/ # => 14
s =~ /now/ # => 4
s =~ /cat/ # => nil

If the String matches the expression, the operator returns the offset, and if it doesn't, it returns nil. It's slightly more complicated than that: see documentation here; it's a method in the String class.

3
  • 4
    Documentation is useless. Been searching for 45 minutes, this is the best explanation I've come across. Thank you.
    – Padawan
    Commented Sep 10, 2015 at 16:23
  • Important point aka (NB): only works on strings not numbers.
    – Gary
    Commented Sep 1, 2018 at 5:42
  • Also, that it matches the "first substring" only as per the documentation: "Returns the Integer index of the first substring that matches the given regexp, or nil if no match found:" Commented Jan 11, 2021 at 22:32
19

=~ is an operator for matching regular expressions, that will return the index of the start of the match (or nil if there is no match).

See here for the documentation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.