From: Brian Candler Date: 2003-05-23T17:05:24+09:00 Subject: Re: why is "does" missing from this sub!-stitution? On Fri, May 23, 2003 at 08:44:16AM +0900, Dave Oshel wrote: > Maybe so, but this works as expected: > > `/sw/bin/fortune -m Nillity`.each { |x| > x.sub!( /(_+\010+)([a-zA-Z]+\b)/, "" + '\2' + "" ) > print x > } > > Maybe it's a bug ... or a feature ... or a bug ... or a bug AND a > feature ... ;-) It's definitely a feature and not a bug. $2 behaves like a regular variable, and as you've seen, you have to use normal string interpolation #{...} to insert it. If $2=="foo" and you write the string "#{$2}" then it is interpolated as "foo", and *then* the resulting string is what you are passing as a parameter to 'sub'. If $2 is nil, then you pass "". So sub has no idea where to substitute any value. However the string '\2' is treated as a special case by sub itself. When it sees that sequence, instead of inserting \ and 2 into the result, it inserts the value of $2. It would be very strange if there were strings with some sort of 'deferred interpolation', i.e. the string contained the sequence '#{expr}' but expr is re-evaluated every time you read the string. Ruby is flexible enough that you could implement that if you wanted though! Regards, Brian.