ruby operator "=~"

103,705

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
103,705
kamen raider
Author by

kamen raider

Updated on May 08, 2020

Comments

  • kamen raider
    kamen raider almost 4 years

    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?

    • Jonas Elfström
      Jonas Elfström about 13 years
      If you want to play around with Ruby regular expression I can recommend rubular.com
    • ryenus
      ryenus over 9 years
      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.
  • Padawan
    Padawan over 8 years
    Documentation is useless. Been searching for 45 minutes, this is the best explanation I've come across. Thank you.
  • Gary
    Gary over 5 years
    Important point aka (NB): only works on strings not numbers.
  • Alien Life Form
    Alien Life Form over 3 years
    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:"