Reputation: 5065
Simple question, but I can't find simple answer
I have a string
str = 'a&b'
I need to replace & to \&
str
>>> a\&b
In php I can do it like this
str_replace('&', '\\&', $str); \\ >>> a\&b
But in ruby this not working
str.gsub('&', '\\&')
>>> a&b
Upvotes: 2
Views: 1906
Reputation: 42899
A solution using a block:
> puts 'a&b'.gsub('&') { '\&' }
a\&b
In the block form, backreferences prefixed with \
are not interpreted, as is the case in the replacement parameter of gsub
.
In the block form, there are $n, $&... variables available instead.
In the form of gsub you are using, the double-backslash must be escaped with yet another backslash.
Upvotes: 4
Reputation: 6255
2.0.0-p0 :018 > "a&b".gsub('&', '\\\&')
=> "a\\&b"
2.0.0-p0 :019 > _.chars.to_a
=> ["a", "\\", "&", "b"]
2.0.0-p0 :023 > puts "a&b".gsub('&', '\\\&')
a\&b
Upvotes: 4