Behaviour of named captures in Regexp#=~ vs. Regexp#match

Here is a transscript of my irb session:

irb(main):030:0> xx=88
=> 88
irb(main):031:0> /(?<xx>\d+)/.match('ab12345tz')
=> #<MatchData "12345" xx:"12345">
irb(main):032:0> xx
=> 88
irb(main):033:0> /(?<xx>\d+)/ =~ ('ab12345tz')
=> 2
irb(main):034:0> xx
=> "12345"

Both pattern match succeed (not surprisingly, because it is the same
pattern and the same string). In the first case, xx is unchanged. In the
second case, xx is changed. Why does match behave different to =~ in
this respect?

Ronald F. wrote in post #1184752:

Here is a transscript of my irb session:

irb(main):030:0> xx=88
=> 88
irb(main):031:0> /(?<xx>\d+)/.match('ab12345tz')
=> #<MatchData "12345" xx:"12345">
irb(main):032:0> xx
=> 88
irb(main):033:0> /(?<xx>\d+)/ =~ ('ab12345tz')
=> 2
irb(main):034:0> xx
=> "12345"

Both pattern match succeed (not surprisingly, because it is the same
pattern and the same string). In the first case, xx is unchanged. In the
second case, xx is changed. Why does match behave different to =~ in
this respect?

m=/(?\d+)/.match(‘ab12345tz’)
=> #<MatchData “12345” xx:“12345”>
m[“xx”]
=> “12345”

Yes, I can extract the value for xx from MatchData, but the question
is, why is in one case my local variable xx already set to the matched
value, and in the other case it is not.

One might argue that Regexp#match can not create a local variable (xx)
on the caller side, because this is impossible in Ruby; but if this is
the reason, why can =~ do it? Actually

re =~ str

is just syntactic sugar for re.=~(str), i.e. the instance method =~ is
invoked. That is, =~ is not some magical keyword known to the Ruby
compiler, but just one of the methods in Regexp. The situation is the
same, but =~ can create the variable xx. How is this possible?

re =~ str is not just simply syntactic sugar.
as you can see the parser does some magic there.
(also checkout the $2 - $9 global variables)

your case is already documented:
http://ruby-doc.org/core-2.3.1/Regexp.html

===
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.

why is in one case my local variable xx already set to the
matched value, and in the other case it is not.

This is a bit of magic behaviour e. g. the mentioned global
variables $2 etc… - some variables get set automatically.

That it is, however had, assigned to local variables with
corresponding names, that was new to me as well. (Or perhaps
the documentation means the value of the variable rather
than the name itself? Are local variables really automagically
set there?)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs