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