puts "\\".gsub("\\", "\\\\")

M

martinus

Hello, I have a mini-ruby quiz. Guess what this line of code writes to
the console, then try it for yourself:

puts "\\".gsub("\\", "\\\\")

Why is that so?

Martin
 
P

Peña, Botp

From: martinus [mailto:[email protected]]=20
# Hello, I have a mini-ruby quiz. Guess what this line of code writes to
# the console, then try it for yourself:
# puts "\\".gsub("\\", "\\\\")

puts "\\".gsub("\\", "\\\\")
\
#=3D> nil

# Why is that so?

faq. escaping the escape in sub/gsub. search the archives.

maybe you want something like,=20

puts "\\".gsub("\\"){"\\\\"}
\\
#=3D> nil

ie, use block wc is a lot more handy.

kind regards -botp
 
S

Simon Krahnke

* martinus said:
Hello, I have a mini-ruby quiz. Guess what this line of code writes to
the console, then try it for yourself:

puts "\\".gsub("\\", "\\\\")

Why is that so?

Well, it's an faq. In short: The backslash is special in strings *and*
in the replacement text. So for every literal backslash you need four
backslashes, which is quite unreadable. If you don't need \1 and Co you
better use the block form: gsub("\\") { "\\\\" }.

mfg, simon .... hth
 
R

Rick DeNatale

Well, it's an faq. In short: The backslash is special in strings *and*
in the replacement text. So for every literal backslash you need four
backslashes, which is quite unreadable. If you don't need \1 and Co you
better use the block form: gsub("\\") { "\\\\" }.

Another thing which trips up newbies, and sometimes not so newbies, is
the difference between the contents of a sring, and the 'inspect'
presentation of a string, particularly when the string contains
escapes:

irb(main):001:0> puts "\\"
\
=> nil
irb(main):002:0> p "\\"
"\\"
=> nil

The point is that the literal string "\\" only contains one character.
The puts method shows you the contents of the string, while p (which
is practically equivalent to puts string.inspect produces a literal
representation.
 

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

Forum statistics

Threads
473,787
Messages
2,569,629
Members
45,331
Latest member
ElaneLyttl

Latest Threads

Top