ruby operator "=~"
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.
kamen raider
Updated on May 08, 2020Comments
-
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 hasregexs = (/\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 about 13 yearsIf you want to play around with Ruby regular expression I can recommend rubular.com
-
ryenus over 9 yearsCan 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 over 8 yearsDocumentation is useless. Been searching for 45 minutes, this is the best explanation I've come across. Thank you.
-
Gary over 5 yearsImportant point aka (NB): only works on strings not numbers.
-
Alien Life Form over 3 yearsAlso, 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:"