From: Rick DeNatale Date: 2008-04-24T22:15:33+09:00 Subject: Re: puts "\\".gsub("\\", "\\\\") On Thu, Apr 24, 2008 at 8:35 AM, Simon Krahnke wrote: > * martinus (11:53) schrieb: > > > > > 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("\\") { "\\\\" }. 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. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/