Gsub and backslashes

Say I want to replace all occurrences of \ in a string with \:

test = “a string with \ a backslash”
puts test.gsub(/\/, “\\”) #no worky
=> a string with \ a backslash

puts test.gsub(/\/, “\\\”) #why does this work?
=> a string with \ a backslash

Why does the replacement string have to be six backslashes? Hopefully
this is really simple and I’m just being dense…

John W. schrieb:

this is really simple and I’m just being dense…

Ooops

irb(main):005:0> puts “a string with \ a backslash”.gsub(/\/,
“\\\\”)
a string with \ a backslash

This works as expected, but why it works with ‘’*6 I don’t understand.

Wolfgang Nádasi-Donner

John W. wrote:

Say I want to replace all occurrences of \ in a string with \:

This is a FAQ. Please search the mailing list archives and the web;
there have been numerous discussions of it, articles written about it,
and it’s addressed in the free online version of Programming Ruby.

Definitely come back with more questions if you really can’t find the
answer online, though.

Wolfgang Nádasi-Donner schrieb:

Ooops

irb(main):005:0> puts “a string with \ a backslash”.gsub(/\/, “\\\\”)
a string with \ a backslash

This works as expected, but why it works with ‘’*6 I don’t understand.

Even after looking to “Programming Ruby - Second Edition”, and several
other
places, I have no idea why it works with ‘\\\’, and other strange
things like
this:

irb(main):001:0> x = “a\b”
=> “a\b”
irb(main):002:0> puts x
a\b
=> nil
irb(main):003:0> puts x.gsub(/\/, ‘+\\\+’)
a+\b
=> nil
irb(main):004:0> puts x.gsub(/\/, ‘+\\\\+’)
a+\+b
=> nil
irb(main):005:0> puts x.gsub(/\/, ‘+\\\t’)
a+\tb
=> nil
irb(main):006:0> puts x.gsub(/\/, ‘+\\\\t’)
a+\tb
=> nil

Especially if I take the following into account:

irb(main):001:0> x = ‘\\’
=> “\\”
irb(main):002:0> puts x
\
=> nil
irb(main):003:0> puts Regexp.escape(x)
\\
=> nil
irb(main):004:0> Regexp.escape(x) == ‘\\\\’
=> true
irb(main):005:0> Regexp.escape(x) == ‘\\\’
=> false

Wolfgang Nádasi-Donner

John W. wrote:

this is really simple and I’m just being dense…
puts test.gsub(/\/, ‘&&’)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs