evan_tech

Previous Entry Share Flag Next Entry
11:20 pm, 14 Nov 06

ruby wart: escaping apostrophes

Suppose I wanna escape all apostrophes with a backslash.

1. "a'b".gsub(/'/, "\'") ⇒ "a'b" — doesn't work, as \' evaluates to ' in double quotes)
2. "a'b".gsub(/'/, "\\'") ⇒ "abb" — \' is special for gsub (!!!)
3. "a'b".gsub(/'/, "\\\'") ⇒ "abb" — by #1, the \' expands into the same string as #2
4. "a'b".gsub(/'/, "\\\\'") ⇒ "a\\'b" — this works, but ew. And it's not even clear to me why it works. (The output looks wrong but remember Ruby is pretty-printing the single \ as \\ in the output.)

The best way to do it?
"a'b".gsub(/'/){"\\'"} ⇒ "a\\'b"

Yuck.