Ruby gsub doesn't escape single-quotes

user263888 picture user263888 · Feb 1, 2010 · Viewed 12.3k times · Source

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"

Answer

user163365 picture user163365 · Feb 1, 2010

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

"Yaho'o".gsub("'", "\\\\'")