Replace “&” to “\&” in Ruby seems impossible?

ぃ、小莉子 提交于 2020-01-21 05:17:17

问题


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"

回答1:


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

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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/6569359/replace-to-in-ruby-seems-impossible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!