I want to replace all &
characters into \\&
with String.gsub
(or a other method). I\'ve tried several combinations and read an
ruby-1.9.2-p180 :008 > puts "asdf & asdf".gsub(/&/, '\\\&')
asdf \& asdf
I'm going to guess that you're using 1.8. In 1.8, irb
says this:
>> "asdf & asdf".gsub("&", "\\\&")
=> "asdf & asdf"
>> puts "asdf & asdf".gsub("&", "\\\&")
asdf & asdf
And that matches what you're seeing. But, if you add yet another backslash, you get what you're after:
>> puts "asdf & asdf".gsub("&", '\\\\&')
asdf \& asdf
The quadruple backslash approach produces the same singly-escaped ampersand for me in both 1.9.2 and 1.8.7 so turn it up to four (not eleven, just four will do).
Your linked question provides a solution - use the block form of gsub
:
irb(main):009:0> puts "asdf & asdf".gsub("&"){'\&'}
asdf \& asdf