From: Eric Armstrong Date: 2006-07-29T06:50:24+09:00 Subject: Re: Finding "\" in a string Arnaud Bergeron wrote: > On 7/28/06, Eric Armstrong wrote: >> I'm going crazy, right? Surely it is possible >> to find a backslash (\) in a string, and >> replace it with two backslashes. That's simple, >> right? Just gsub("\\", '\\'). That's all there >> is to it. > > irb> puts '\\' > \ > => nil > > You are replacing single slashes with single slashes. > You would think so, wouldn't you? But note that I've used single quotes for the replacement. So it /should/ equate to two backslashes. So I tried four of them in the replacement string. I did so yesterday, in fact, and repeated the experiment today: testpath = "\\foo\\bar" result = testpath.gsub("\\", '\\\\') p result # => "\\foo\\bar" (s/b "\\\\foo\\\\bar" puts result # => \foo\bar (s/b \\foo\\bar) Notice that the results are unchanged. So I tried a simple character: testpath.gsub("\\", 'r') That worked as expected: "\\foo\\bar" \foo\bar "rfoorbar" rfoorbar So it would appear that something strange is happening in the evaluation of the gsub replacement string. >> Except that... >> >> #!/usr/bin/env ruby >> >> testpath = "\\foo\\bar" >> p testpath # => "\\foo\\bar" --representation >> puts testpath # => \foo\bar --what you see >> >> result = testpath.gsub("\\", '\\') >> p result # => "\\foo\\bar" >> (represenation unchanged. Should be "\\\\foo\\\\bar") >> >> puts result # => \foo\bar >> (unchanged. should be \\foo\\bar) >> >> I've tried lots of gsub variations, like >> /\\/, '\\', "\\\\", and anything else I could >> think of that came even close to being sensible, >> but I've yet to find anything that works. >> >> My workaround will be to add a sed script to >> filter the input. But surely that isn't necessary. >> Is it? >> > > >