From: kane.sub@... Date: 2007-05-31T00:17:23+09:00 Subject: Re: Substituting Variables Hello Andrew, Use double quotes and escape slashes. '30 May 2007'.sub( /(\d+)\s(\w+)\s(\d+)/, "\\1 #{var} \\3" ) Wednesday, May 30, 2007, 8:09:29 PM, you wrote: AS> Hello, AS> I am running into difficulties trying to use a variable in a AS> substitution. Here's an example: AS> var = 'October' AS> '30 May 2007'.sub( /(\d+)\s(\w+)\s(\d+)/, '\1 #{var} \3' ) AS> Here I would like to get '30 October 2007'. The back-references, AS> i.e. \1 and \3, only work within single quotation marks. But the AS> interpolation only works within double quotation marks. What to do? AS> Here's an example in IRB: >>> var = 'October' >>> re = /(\d+)\s(\w+)\s(\d+)/ >>> '30 May 2007'.sub(re, '\1 #{var} \3') =>> "30 \#{var} 2007" >>> '30 May 2007'.sub(re, "\1 #{var} \3") =>> "\001 October \003" >>> '30 May 2007'.sub(re, "#{$1} #{var} #{$3}") =>> "30 October 2007" AS> Actually that last one does what I want -- but according to the AS> Pickaxe[1] $1 and friends aren't supposed to work and in fact it AS> doesn't work in my Ruby class. So I think IRB is flattering to deceive. AS> [1] String.gsub: "If a string is used as the replacement, special AS> variables from the match (such as $& and $1) cannot be substituted AS> into it, as substitution into the string occurs before the pattern AS> match starts. However, the sequences \1, \2, and so on may be used AS> to interpolated successive groups in the match." AS> I have found a workaround but I'm hoping there's a better way: >>> '30 May 2007'.sub(re, '\1' + " #{var} " + '\3') =>> "30 October 2007" AS> Any insight would be much appreciated. AS> Thanks and regards, AS> Andy Stewart -- Best regards, kane mailto:kane.sub@inbox.uz