From: Brian Candler Date: 2003-05-24T16:51:30+09:00 Subject: Re: why is "does" missing from this sub!-stitution? On Sat, May 24, 2003 at 07:31:51AM +0900, dblack@superlink.net wrote: > It's interesting, though, that $2 hasn't been (re)evaluated by the > time the second argument to #sub is evaluated. Compare with: > > irb(main):001:0> "abcdef".sub(s="d",s.upcase) > => "abcDef" I don't see any magic there: 1. The first parameter is evaluated. It evaluates to "d", and has the side-effect of setting s. 2. The second parameter is evaluated. It evaluates to "D" 3. The method call is made: "abcdef".sub("d","D") > 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. The main reason is expression evaluation sequencing: the arguments to gsub! are each evaluated individually, and *then* the results of those evaluations are passed to gsub! So "#{$1}" is evaluated, which generates a new string object containing "", and a reference to that object is passed in to gsub! as its second parameter, as part of the method call. > But then \2 wouldn't be meaningful.... \2 is a magic sequence to gsub. What it does is: - match on the regular expression - for each match, replace the match with the dest string, but first replace \1, \2 etc in the dest string with match[1], match[2] etc. gsub could have been written to interpret a literal "$1" or "$2" in the same way, but then if you did actually want to insert a "$" there would be more escaping rules to be learned. Regards, Brian.