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

  • blog moved

    As described elsewhere, I've quit LiveJournal. If you're interested in my continuing posts, you should look at one of these (each contains feed…

  • dremel

    They published a paper on Dremel, my favorite previously-unpublished tool from the Google toolchest. Greg Linden discusses it: "[...] it is capable…

  • treemaps

    I finally wrote up my recent adventures in treemapping, complete with nifty clickable visualizations.

  • 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.