Replace single quote with backslash single quote

The %q delimiters come in handy here:

# %q(a string) is equivalent to a single-quoted string
puts "Cote d'Ivoir".gsub("'", %q(\\\')) #=> Cote d\'Ivoir

The problem is that \' in a gsub replacement means "part of the string after the match".

You're probably best to use either the block syntax:

a = "Cote d'Ivoir"
a.gsub(/'/) {|s| "\\'"}
# => "Cote d\\'Ivoir"

or the Hash syntax:

a.gsub(/'/, {"'" => "\\'"})

There's also the hacky workaround:

a.gsub(/'/, '\#').gsub(/#/, "'")

Tags:

String

Ruby