Does the order on the = = operator matter?

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

/regex/ =~ "some_string_with_regex"

"some_string_with_regex" =~ /regex/

+6
source share
1 answer

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

If =~ used with a regexp literal with named captures, strings (or nil) are assigned to local variables called capture names.

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

...

Assignment does not occur if the regular expression is placed on the right side.

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

String # ~ =

+5
source

Source: https://habr.com/ru/post/895419/


All Articles