What is the "=~" operator in Ruby?

RubyOperators

Ruby Problem Overview


I saw this on a screencast and couldn't figure out what it was. Reference sheets just pile it in with other operators as a general pattern match operator.

Ruby Solutions


Solution 1 - Ruby

It matches string to a regular expression.

'hello' =~ /^h/ # => 0

If there is no match, it will return nil. If you pass it invalid arguments (ie, left or right-hand sides are not correct), it will either throw a TypeError or return false.

Solution 2 - Ruby

From ruby-doc :

str =~ obj => fixnum or nil

Match—If obj is a Regexp, use it as a pattern to match against str, and returns the offset position the match starts, or nil if there is no match. Otherwise, invokes obj.=, passing str as an argument. The default = in Object returns false.

"cat o' 9 tails" =~ /\d/   #=> 7
"cat o' 9 tails" =~ 9      #=> false

Solution 3 - Ruby

Well, the reference is correct, it is the "matches this regex" operator.

if var =~ /myregex/ then something end

Solution 4 - Ruby

As the other answers already stated, =~ is the regular expression vs string match operator.

Note: The =~ operator is not commutative

Please consider the note below from the ruby doc site, as I have seen yet only the first form

str =~ regexp 

used in the other answers:

> Note: str =~ regexp is not the same as regexp =~ str. Strings captured > from named capture groups are assigned to local variables only in the > second case.

Here is the documentation for the second form: link

Solution 5 - Ruby

Regular expression string matching. Here's a detailed list of operators: http://phrogz.net/programmingruby/tut_expressions.html#table_7.1

Solution 6 - Ruby

Regular expression string matching:

puts true if url =~ /google.com/

You can read '=~' as 'is matching'.

Solution 7 - Ruby

I believe this is a pattern matching operator used with regex.

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
QuestionCCSabView Question on Stackoverflow
Solution 1 - RubyealdentView Answer on Stackoverflow
Solution 2 - RubyJu NogueiraView Answer on Stackoverflow
Solution 3 - RubyTesserexView Answer on Stackoverflow
Solution 4 - RubymvwView Answer on Stackoverflow
Solution 5 - RubyCurtisView Answer on Stackoverflow
Solution 6 - RubyErikView Answer on Stackoverflow
Solution 7 - RubyAndrew HubbsView Answer on Stackoverflow