Backslashes

H

Han Holl

------=_Part_2456_4241297.1128002290320
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hi,

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

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

Cheers,

Han Holl

------=_Part_2456_4241297.1128002290320--
 
T

ts

H> 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
 
A

Austin Ziegler

Hi,

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

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

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
 
G

Gavin Kistner

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
 
H

Han Holl

------=_Part_2808_26441850.1128005622184
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

See "Explanation for the multitude of backslashes" on http://
rubygarden.org/ruby?RegexpCookbook<http://rubygarden.org/ruby?RegexpCookb= ook>

Thanks to you all.
Pickaxe2 seems to be silent about this. Maybe pickaxe3 ?

Cheers,

Han Holl

------=_Part_2808_26441850.1128005622184--
 
G

Gennady Bystritksy

Han said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top