30

I don't understand what is going on here. How should I feed gsub to get the string "Yaho\'o"?

>> "Yaho'o".gsub("Y", "\\Y")
=> "\\Yaho'o"
>> "Yaho'o".gsub("'", "\\'")
=> "Yahooo"

3 Answers3

39

\' means $' which is everything after the match. Escape the \ again and it works

"Yaho'o".gsub("'", "\\\\'")
user163365
  • 1,317
  • 9
  • 14
2
"Yaho'o".gsub("'", "\\\\'")

Because you're escaping the escape character as well as escaping the single quote.

mopoke
  • 10,555
  • 1
  • 31
  • 31
1

This will also do it, and it's a bit more readable:

def escape_single_quotes(str)
  str.gsub(/'/) { |x| "\\#{x}" }
end

If you want to escape both a single-quote and a backslash, so that you can embed that string in a double-quoted ruby string, then the following will do that for you:

def escape_single_quotes_and_backslash(str)
  str.gsub(/\\|'/) { |x| "\\#{x}" }
end
jsears
  • 4,511
  • 2
  • 31
  • 36