From: matt@... (matt neuburg) Date: 2009-03-18T05:17:30+09:00 Subject: Re: Interpolating $1, etc., from within a gsub block Lloyd Zusman wrote: > I'm trying to use the block form of gsub in order to do substitution > involving an interpolation stored within a variable, but I can't > figure out how to get it to work. Here's a simplified case of what > I'm trying to do: > > $fromre = Regexp.compile(ARGV[0]) > $repl = ARGV[1] > $replcount = 0 > > string = "... something arbitrary ..." > > string.gsub!($fromre) { > |x| > $replcount += 1 > $repl > } > > As you can see, the regexp comes in on the command line, as well as > the replacement. I want to do this substution using the block form so > I can count the number of replacements that were made. > > This works as long as $repl doesn't contain any references to matched > patterns. However, if this program is called 'myprog' and I do the > following, the replacement of $1 with the indicated subexpression > doesn't occur: > > myprog 'abc(\S+)def' 'NEW-$1-MATCH' > > In other words, if the string being substituted is this, "abcFOOBARdef", > the result is not "NEW-FOOBAR-MATCH" as I would like it to be, but rather, > "NEW-$1-MATCH". > $fromre = /abc(\S+)def/ $repl = '"NEW-#{$1}-MATCH"' string = "abcFOOBARdef" string.gsub!($fromre) { |x| instance_eval($repl) } I don't like it any better than you do...! :) m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Leopard - http://www.takecontrolbooks.com/leopard-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com