On Mon, 2009-09-07 at 17:36 +0900, Fabian Streitel wrote:
> hi,
> trying to solve someones mailinglist posted problem, I just created my own.
> Why do 2 backslashes produce the same result as 4 and 6 the same as 8?
> 
> 014:0> 'ab'.gsub('a', '\\')
>     => "\\b"
> 015:0> 'ab'.gsub('a', '\\\\')
>     => "\\b"
> 016:0> 'ab'.gsub('a', '\\\\\\')
>     => "\\\\b"
> 017:0> 'ab'.gsub('a', '\\\\\\\\')
>     => "\\\\b"
> 018:0> RUBY_DESCRIPTION
>     => "ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-linux]"
> 
> Doesn't that strike anyone as odd?
> Greetz!



Be careful with gsub, it does a lot of magic. From the documentation:

   If a string is used as the replacement, special variables from the
   match (such as +$&+ and +$1+) cannot be substituted into it, as
   substitution into the string occurs before the pattern match
   starts. However, the sequences +\1+, +\2+, and so on may be used to
   interpolate successive groups in the match.

To fix, put the replacement into a block:

irb(main):001:0> s = '\\'
=> "\\"
irb(main):002:0> s.size
=> 1
irb(main):003:0> s = s * 10
=> "\\\\\\\\\\\\\\\\\\\\"
irb(main):004:0> s.size
=> 10
irb(main):005:0> 'a'.gsub('a', s).size
=> 5
irb(main):006:0> 'a'.gsub('a') { s }.size
=> 10
irb(main):007:0> 'a'.gsub('a') { s }
=> "\\\\\\\\\\\\\\\\\\\\"
irb(main):008:0> 'a'.gsub('a', s)
=> "\\\\\\\\\\"



Martin