Backslashes

Hi,

Why does
'\\'.gsub('\\','\\\\').size
produce 1 ?

Is this a bug, or should it be specially documented ?

Cheers,

Han Holl

Is this a bug, or should it be specially documented ?

Well, it's documented but in the FAQ

Regexp.quote('\\') escapes a backslash.

It gets trickier if you're using sub and gsub, Say you write gsub(/\\/,
'\\\\'), hoping to replace each backslash with two. The second argument is
converted to '\\' in syntax analysis. When the substitution occurs, the
regular expression engine converts this to '\', so the net effect is to
replace each single backslash with another single backslash. You need to
write gsub(/\\/, '\\\\\\')!

Guy Decoux

It's not a bug, and it's relatively well known. I recommend:

  '\\'.gsub(/\\/) { "\\\\" }.size

The *trick* is that strings consider \ special, so to use special
regexp values (like \1), you need \\1. So to get \\, you actually need
\\\\\\\\ (yes, eight of them). The first round of interpolation
(string) will result in \\\\; the second round of interpolation
(regexp substitution values) will result in \\.

-austin

···

On 9/29/05, Han Holl <han.holl@gmail.com> wrote:

Hi,

Why does
'\\'.gsub('\\','\\\\').size
produce 1 ?

Is this a bug, or should it be specially documented ?

--
Austin Ziegler * halostatue@gmail.com
               * Alternate: austin@halostatue.ca

See "Explanation for the multitude of backslashes" on http://rubygarden.org/ruby?RegexpCookbook

···

On Sep 29, 2005, at 7:58 AM, Han Holl wrote:

Why does
'\\'.gsub('\\','\\\\').size
produce 1 ?

Is this a bug, or should it be specially documented ?

Pickaxe2 seems to be silent about this. Maybe pickaxe3 ?

Cheers,

Han Holl

···

On 9/29/05, Gavin Kistner <gavin@refinery.com> wrote:

On Sep 29, 2005, at 7:58 AM, Han Holl wrote:
> Why does
> '\\'.gsub('\\','\\\\').size
> produce 1 ?
>
> Is this a bug, or should it be specially documented ?

See "Explanation for the multitude of backslashes" on http://
rubygarden.org/ruby?RegexpCookbook<http://rubygarden.org/ruby?RegexpCookbook&gt;

Thanks to you all.

Han Holl wrote:

···

On 9/29/05, Gavin Kistner <gavin@refinery.com> wrote:

On Sep 29, 2005, at 7:58 AM, Han Holl wrote:

Why does
'\\'.gsub('\\','\\\\').size
produce 1 ?

Is this a bug, or should it be specially documented ?

See "Explanation for the multitude of backslashes" on http://
rubygarden.org/ruby?RegexpCookbook<http://rubygarden.org/ruby?RegexpCookbook&gt;

Thanks to you all.

Pickaxe2 seems to be silent about this. Maybe pickaxe3 ?

Cheers,

Han Holl

You cannot have one book cover EVERY aspect of a subject. People will hate when it grows to several volumes. That's where online resouces come in handy.

Gennady.

Pickaxe 2 very clearly discusses this on page 75.

···

On Sep 29, 2005, at 8:53 AM, Han Holl wrote:

Pickaxe2 seems to be silent about this. Maybe pickaxe3 ?