ruby operator "=~"

RubyOperators

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

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 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkamen raiderView Question on Stackoverflow
Solution 1 - RubyMike LewisView Answer on Stackoverflow
Solution 2 - RubyDigitalRossView Answer on Stackoverflow
Solution 3 - RubyTim DestanView Answer on Stackoverflow