Ruby WTF? Escaping single quotes in Ruby using gsub
2.2.1 :002 > "Doesn't work".gsub("'", "\\'")
I did a bit of investigation (read: Stack Overflow) and found that
\' is a special escape sequence in the gsub replacement – it’s a backreference that represents
$', the characters that match after the single quote.
In order to fix this bug, you must escape the backslash within gsub as so:
2.2.1 :003 > "Doesn't work".gsub("'", "\\\\'")
Nota bene: The double backslash returned by IRB is actually a single escaped backslash – it hasn’t generated another one.
gsub first escapes everything as a Ruby string, then it parses the result of that string as a regex. It’s not documented well at all – I couldn’t find anything on this in the documentation.
Ruby’s such a weird language.