Evan Martin (evan) wrote in evan_tech,
Evan Martin

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"

Tags: ruby

  • your vcs sucks

    I've been hacking on some Haskell stuff lately that's all managed in darcs and it's reminded me of an observation I made over two years ago now (see…

  • jaunty upgrade

    Upgraded to Ubuntu Jaunty. X hung with garbage on the screen after rebooting. Booted into "restore mode" (I forget the exact name), it gave me a…

  • ubuntu summit

    There's an Ubuntu summit going on in Mountain View next week. I'll be there Monday and plan to meet up with someone who's interested in packaging…

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.