141

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?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
kamen raider
  • 1,513
  • 2
  • 10
  • 6
  • 2
    If you want to play around with Ruby regular expression I can recommend http://rubular.com/ – Jonas Elfström Apr 25 '11 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 Oct 24 '14 at 05:07

3 Answers3

202

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
47

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • 4
    Documentation is useless. Been searching for 45 minutes, this is the best explanation I've come across. Thank you. – Padawan Sep 10 '15 at 16:23
  • Important point aka (NB): only works on strings not numbers. – Gary Sep 01 '18 at 05: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:" – Alien Life Form Jan 11 '21 at 22:32
18

=~ 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.

Tim Destan
  • 2,028
  • 12
  • 16