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.
-
14@user97370: Quite often ruby docs are used as a flippant solution to answer all questions without realizing that ruby docs is not always an easy-to-understand site. Quite often (most of the time) I start with ruby docs, fail to understand the encrypted, anemic explanations then Google, only to find there are also no solutions on Google. One does not simply Google "Ruby =~" or "Ruby =~ method" or "Ruby =~ operator" to get an answer. It would be nice to see fewer people throw ruby docs out as a lazy solution and to see more in depth answers that actually help. – Padawan Sep 10 '15 at 16:07
7 Answers
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
.

- 3,677
- 1
- 25
- 26
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

- 5
- 2

- 8,435
- 2
- 29
- 33
-
2"returns the position the match starts", is the important bit for me :) Been scouring Google for an answer.. found it here thanks! – David K May 09 '12 at 19:57
-
Why does the second example return false? Is it because `9` isn't a string? – Jon Schneider Feb 20 '18 at 16:38
-
yes, to test for the string "9" you would need to enclose it in forward slashes so it's interpreted like a regex: /9/ – ohhh May 17 '19 at 10:55
Well, the reference is correct, it is the "matches this regex" operator.
if var =~ /myregex/ then something end

- 17,166
- 5
- 66
- 106
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 asregexp =~ 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

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

- 3,931
- 1
- 19
- 26
Regular expression string matching:
puts true if url =~ /google.com/
You can read '=~' as 'is matching'.

- 4,268
- 5
- 33
- 49