From: Robert Klemme Date: 2010-11-22T17:38:37+09:00 Subject: Re: gsub and backslashes On Mon, Nov 22, 2010 at 12:27 AM, Ammar Ali wrote: > On Sun, Nov 21, 2010 at 11:02 PM, Brian Candler wrote: >> Ralph Shnelvar wrote in post #962847: >>>   "\\1\\2\\3".gsub(/\\/,"\\\\") >> >> Here you are replacing one backslash with one backslash. >> >> The trouble is, in the *replacement* string, '\1' has a special meaning >> (insert the value of the first capture). Because of this, a literal >> backslash is backslash-backslash. > > That's a keen observation, but the fact that they happen to be > back-references doesn't seem to play a part in this situation. > >>> "\\a\\b\\c".gsub(/\\/,"\\\\") > => "\\a\\b\\c" >>> "\\a\\b\\c".gsub(/\\/,"\\\\\\") > => "\\\\a\\\\b\\\\c" The key point to understand IMHO is that a backslash is special in replacement strings. So, whenever one wants to have a literal backslash in a replacement string one needs to escape it and hence have to backslashes. Coincidentally a backslash is also special in a string (even in a single quoted string). So you need two levels of escaping, makes 2 * 2 = 4 backslashes on the screen for one literal replacement backslash. Additionally people are often confused by the fact that IRB by default uses #inspect for showing expression values which will display twice as much backslashes as are present in the string. :-) Can we please make a big red sticker and put it on every Ruby installer and source tar to inform people of this and the local variable method ambiguity. These two seem to be the issues that pop up most of the time. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/