From: Thomas Hurst Date: 2002-03-21T02:06:33+09:00 Subject: Re: Regex backreference in method "sub" * Kirk Lowery (klowery@wts.edu) wrote: > line.sub!(/(str)ing/,"#{$1}") > Apparently, $1 never gets set to the matched group until *after* > exiting the sub method. Why not? How do I do this kind of substution? Look at the order of evaluation: line.sub!(/(str)ing/,"#{$1}") -> /(str)ing/ becomes a Regexp object instance -> "#{$1}" becomes a String object instance -> both are passed to line#sub!() So it's equivilent to: a = Regexp.new('(str)ing') b = String.new("#{$1}") line.sub!(a, b) A different ordering is meaningless (although you can swap a and b). The correct way to talk about backreferences is the traditional \ operator: line.sub!(/(str)ing/,'\1') Since this is evaluated by the regexp engine rather than the string object. Remember you need to escape it in double quotes, i.e. "\\1". -- Thomas 'Freaky' Hurst - freaky@aagh.net - http://www.aagh.net/ - The fact that boys are allowed to exist at all is evidence of a remarkable Christian forbearance among men. -- Ambrose Bierce