Bug #7042

String#=~ is not equal to Regexp#=~

Added by Hanmac (Hans Mackowiak) over 7 years ago. Updated over 7 years ago.

Target version:
ruby -v:
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]


i found out that string =~ regexp is not equal to regexp =~ string
when you use named captures:

"6:15 PM" =~ /(?\d+):(?\d+) (?A|P)M/; p hour,minute,pm # works not
/(?\d+):(?\d+) (?A|P)M/ =~ "6:15 AM"; p hour,minute,pm # works

i wonder why is that so ?

Updated by stomar (Marcus Stollsteimer) over 7 years ago

From the documentation for Regexp:

"When named capture groups are used with a literal regexp on the left-hand side of an expression and the =~ operator, the captured text is also assigned to local variables with corresponding names."

Of course, this does not really answer the question regarding the "why".


Updated by stomar (Marcus Stollsteimer) over 7 years ago

...and further down in the Regexp docs:

"This assignment is implemented in the Ruby parser. The parser detects ‘regexp-literal =~ expression’ for the assignment. The regexp must be a literal without interpolation and placed at left hand side."

"The assignment does not occur if the regexp is not a literal."

Updated by mame (Yusuke Endoh) over 7 years ago

  • Status changed from Open to Rejected

Because this is a kind of assignment, the value is in the right side and the variable is in the left side... we thought.

This is actually intentional. Closing.
You can open a feature request to add a pattern to regexp assignment, if you wish.

Yusuke Endoh

Also available in: Atom PDF