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

落爺英雄遲暮 提交于 2019-11-30 22:45:56

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

irb(main):009:0> 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).

ruby-1.9.2-p180 :008 > puts "asdf & asdf".gsub(/&/, '\\\&')
asdf \& asdf
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!