redexp
redexp

Reputation: 5065

Ruby: replace in string ampersand to backslash with ampersand

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

Answers (2)

SirDarius
SirDarius

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

DNNX
DNNX

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

Related Questions