Is there any difference besides coding style for the following two statements?
/regex/ =~ "some_string_with_regex"
"some_string_with_regex" =~ /regex/
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#~=
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With