f00860
f00860

Reputation: 3576

Replace "&" to "\&" in Ruby seems impossible?

I want to replace all & characters into \& with String.gsub (or a other method). I've tried several combinations and read another question here, but nothing is gonna work.

  "asdf & asdf".gsub("&", "\\\&") => "asdf & asdf"

Upvotes: 6

Views: 2580

Answers (3)

mu is too short
mu is too short

Reputation: 434685

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).

Upvotes: 2

Chowlett
Chowlett

Reputation: 46667

Your linked question provides a solution - use the block form of gsub:

irb(main):009:0> puts "asdf & asdf".gsub("&"){'\&'}
asdf \& asdf

Upvotes: 11

Nicolas Viennot
Nicolas Viennot

Reputation: 3969

ruby-1.9.2-p180 :008 > puts "asdf & asdf".gsub(/&/, '\\\&')
asdf \& asdf

Upvotes: 2

Related Questions