From: dblack@... Date: 2003-05-24T10:23:22+09:00 Subject: Re: why is "does" missing from this sub!-stitution? Hi -- On Sat, 24 May 2003, Dave Thomas wrote: > dblack@superlink.net wrote: > > > My first thought by way of explaining the $2 behavior was: there's > > been no assignment to $2, because the regex has been compiled but the > > match hasn't happened yet. But then \2 wouldn't be meaningful.... So > > I do actually start to wonder why the previous $2 (nil or otherwise) > > persists so long. > > \2 is substituted by .sub (ie, it gets passed in as part of the string, > and .sub looks for and substitutes for it). #$2 is substituted during > the initial parse of the string (before .sub is even called) > > irb(main):008:0> "abcdef".sub(/(..)/, "#$1") > => "cdef" > irb(main):009:0> "abcdef".sub(/(..)/, "#$1") > => "abcdef" I'm with you on the 'what', but I'm still curious about the 'why'. It's true that the replacement string gets parsed before sub is called. But I think "abcdef" gets matched against the regex even before that parse happens. Which means... if the $1,$2 variables reflect the results of the most recent match, then one could argue that by the time the replacement string is parsed, a match has just taken place and $1,$2 should reflect the results of that match. So the order of things seems a little odd: /(..)/.match("abcdef") # match operation, $1 set "abcdef".sub(/(..)/, "#$1") # match operation, $1 *not* set then string parsed, *then* $1 is set David -- David Alan Black home: dblack@superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav