On 1-Nov-07, at 9:47 PM, 7stud -- wrote:

> Is this behavior documented anywhere:
>
> 1)
> puts "fred:smith".gsub(/(\w+):(\w+)/, '\2, \1')
>
> --output:--
> smith, fred
>
> 2)
> puts "abc".gsub(/a(b)(c)/, "a\2\1")
>
> --output:--
> a
>
> The double quotes surrounding the replacement string cause the  
> backslash
> sequences to stop working.  With single quotes the backslash sequences
> work.  I can't find anything in pickaxe2 about that.  .My  
> understanding
> was that double quotes allowed for more substitutions than single
> quotes.  This appears to be a case where double quotes allow fewer
> substitutions than single quotes.
> -- 
> Posted via http://www.ruby-forum.com/.


The double quotes interpolate the \1 and \2 as characters before gsub  
ever sees it.

ratdog:~ mike$ ruby -e 'puts "abc".gsub(/a(b)(c)/, "a\2\1")' | od -c
0000000    a 002 001  \n
0000004

ratdog:~ mike$ irb
irb(main):001:0> 'a\1\2'.length
=> 5
irb(main):002:0> "a\1\2".length
=> 3
irb(main):003:0> "a\2\1"
=> "a\002\001"

the \2 and \1 are interpolated into two single characters in the  
double quotes.

Table 22.2 in The Basic Types says \nnn goes to Octal nnn, and here  
you see 8 (not a valid octal digit) doesn't get treated the same way  
as 1 and 2:

irb(main):004:0> "a\2\1\8"
=> "a\002\0018"

Hope this helps,

Mike

-- 

Mike Stok <mike / stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.