On May 10, 2004, at 11:38 AM, Benedikt Huber wrote:

> On Tue, 06 Apr 2004 23:01:55 +0900, Robert Feldt wrote:
>
>> ts wrote:
>> ...
>>> svg% ruby -e 'p "abcdef".sub(/(.).(..)/, "\\+")'
>>> "cdef"
>>> svg%
>>> ...
>> Yeah, that's right the "last matched group"; I don't use that one much
>> apparently...
> Perhaps I'm missing the point, but what semantic have consecutive
> backslashes substituting a string ?
> I feels like a bug, but probably isn't:
> irb(main):008:0> puts "abcd".sub('abcd',"\\").length
> 1
> irb(main):014:0> puts "abcd".sub('abcd',"\\"*2).length
> 1
> irb(main):009:0> puts "abcd".sub('abcd',"\\"*10).length
> 5
>
> Thx a lot,
> benedikt

normal strings are escaped thusly:

   puts "\\","\\\\","\\\\\\"
\
\\
\\\
     => nil

regexp strings have and extra level of escaping, so that you can 
include literal "\1"'s in your substitution. So, they are escaped 
thusly:

   puts "".sub(//,"\\\\"), "".sub(//,"\\\\\\\\"), 
"".sub(//,"\\\\\\\\\\\\")
\
\\
\\\
     => nil

The somewhat confusing part is that a backslash in a gsub that doesn't 
translate to a substitution expression becomes a literal. So, since 
there is nothing for the  last backslash to escape:

   puts "".sub(//,"\\"), "".sub(//,"\\\\\\"), "".sub(//,"\\\\\\\\\\")
\
\\
\\\
     => nil

... another reason why, as someone pointed out in a thread earlier this 
month, it's handy to only use the block form, and avoid the argument 
form of (g)sub like the plague :)

cheers,
--Mark