From: Robert Klemme Date: 2009-09-07T23:23:54+09:00 Subject: Re: '\\\\\\\\' madness? 2009/9/7 Fabian Streitel : > hi, > trying to solve someones mailinglist posted problem, I just created my own. > Why do 2 backslashes produce the same result as 4 and 6 the same as 8? > > 014:0> 'ab'.gsub('a', '\\') >    => "\\b" > 015:0> 'ab'.gsub('a', '\\\\') >    => "\\b" > 016:0> 'ab'.gsub('a', '\\\\\\') >    => "\\\\b" > 017:0> 'ab'.gsub('a', '\\\\\\\\') >    => "\\\\b" > 018:0> RUBY_DESCRIPTION >    => "ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-linux]" > > Doesn't that strike anyone as odd? Well, not me anyway. :-) You can find a lot of threads about this in the archives... (hint, hint) The short story: you need to keep in mind that there are multiple levels of escaping going on which unfortunately use the same character ("\") as meta character AND output in IRB is done via #inspect. To get a single backslash in a string you need to type two: irb(main):001:0> puts '\\' \ => nil In order to make gsub use a backslash literally (and not interpret it as meta character) you need to have two of them in the string: irb(main):002:0> puts '\\\\' \\ => nil Now, there are some corner cases: your first example uses a replacement string with just a single backslash so it looses its metaness (because there is nothing behind it to escape). This is true for all cases where there is nothing behind it which can be escaped: irb(main):004:0> puts '\1', '\\1' \1 \1 => nil HTH Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/