On Thu, 26 Apr 2007, Lyle Johnson wrote:

> On 4/26/07, Yukihiro Matsumoto <matz / ruby-lang.org> wrote:
> 
> > It was intentional to escape backslashes in replacement string.
> > If it were a bug, how do we escape backslashes?  Any idea?
> 
> Why does his second example:
> 
>    '\\'.gsub('\\', '\\\\\\')
> 
> result in "\\\\" (with four backslashes) instead of "\\\" (with three)?

Well, firstly because you can't have "\\\" because you'd need a char
for the 3rd backslash to quote.  Why is the first case only one (quoted)
backslash?

irb(main):003:0> '\\'.gsub(/\\/,'\\\\')
=> "\\"
irb(main):004:0> '\\'.gsub(/\\/,'\\\\\\')
=> "\\\\"
irb(main):005:0> '\\'.gsub(/\\/,'\\\\\\\\')
=> "\\\\"
irb(main):006:0> '\\'.gsub(/\\/,'\\\\\\\\\\')
=> "\\\\\\"

I seem to remember that the second parameter of gsub gets pushed though
backslash processing twice.  So the double backslash (quoted) in '\\\\'
becomes a single backslash  \ == '\\'.

[I have wished for a string type with NO quoting of ANY characters
for handling backslashes readably, but have no useful suggestions
for what it should be. %b{}, maybe %n{},... ??  In some
circumstances the Exim mail transfer agent's configuration file has
syntax for changing the quoting character within literals. Borrowing
that would mean doing frightful things with the parser, though.  Not
exactly light entertainment for the maintainer.]

        Hugh