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

前端 未结 3 886
孤独总比滥情好
孤独总比滥情好 2020-12-10 19:36

I want to replace all & characters into \\& with String.gsub (or a other method). I\'ve tried several combinations and read an

相关标签:
3条回答
  • 2020-12-10 19:54
    ruby-1.9.2-p180 :008 > puts "asdf & asdf".gsub(/&/, '\\\&')
    asdf \& asdf
    
    0 讨论(0)
  • 2020-12-10 19:56

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

    0 讨论(0)
  • 2020-12-10 20:07

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

    irb(main):009:0> puts "asdf & asdf".gsub("&"){'\&'}
    asdf \& asdf
    
    0 讨论(0)
提交回复
热议问题