Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does order matter on the =~ operator?

Is there any difference besides coding style for the following two statements?

/regex/ =~ "some_string_with_regex"

"some_string_with_regex" =~ /regex/

like image 285
Drew Avatar asked Aug 19 '11 14:08

Drew


1 Answers

Yes, there's a difference. As mentioned on http://www.ruby-doc.org/core/classes/Regexp.html#M001232

If =~ is used with a regexp literal with named captures, captured strings (or nil) is assigned to local variables named by the capture names.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ "  x = y  "
p lhs    #=> "x" 
p rhs    #=> "y"

...

The assignment is not occur if the regexp is placed at right hand side.

"  x = y  " =~ /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
p lhs, rhs # undefined local variable

String#~=

like image 164
Dogbert Avatar answered Nov 12 '22 03:11

Dogbert