From: mike@... (Mike Stok) Date: 2004-01-22T21:00:10+09:00 Subject: Re: gsub oddity? In article , Robert Klemme wrote: > >"Mark J. Reed" schrieb im Newsbeitrag >news:20040121221951.GD16733@mulan.thereeds.org... >> On Thu, Jan 22, 2004 at 06:57:22AM +0900, Ralph Mason wrote: >> > What am I missing here. I am trying to replace a single quote with >the >> > string \' >> >> You're missing an extra level of processing applied to the replacement >> string for gsub in order to let you include parts of what you're >> replacing. > >No, in this case he's missing extra backslashes: > >irb(main):002:0> str='a\'o' >=> "a'o" >irb(main):003:0> str.gsub(/'/, '\\\\\'' ) >=> "a\\'o" >irb(main):004:0> puts str.gsub(/'/, '\\\\\'' ) >a\'o >=> nil > >It does look a bit odd, but the explanation is logical: There are two >levels of escaping involved. The first level is that needed for the ruby >parser to get the expected characters into the replacement string. The >second level is used in order to be able to use a backslash literally in >the substitution string. > >irb(main):005:0> puts '\\\\\'' >\\' >=> nil > >You need two backslashes in the substitution string to prevent gsub from >interpreting the backslash as escape char. That makes four backslashes >when entering the string. The fifth backslash escapes the single quote in >order to be able to include it into the string. You can make life a little easier by picking a quote other than ' to get rid of one backslash e.g. [mike@ratdog mike]$ irb --simple-prompt >> str = "a'o" => "a'o" >> puts str.gsub(/'/, "\\\\'") a\'o => nil It can be tiresome to remember how many times a string will be scanned in a context where \ characters matter, so I prefer using the block form e.g. >> puts str.gsub(/(')/) { |c| "\\#{c}" } a\'o => nil ....but I have never measured whether this is significantly more expensive. Hal, is this a FAQ? "How do I replace ' with \' in a string?" I'm sure that this has come up a few times... Hope this helps, Mike -- mike@stok.co.uk | The "`Stok' disclaimers" apply. http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60 http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA