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…

  • perl people, explain your language to me

    Every time I use perl I feel mildly positive about it right up until I encounter CPAN. I've never managed to make CPAN work, despite the multitude of…

  • dns attack of doom

    If I've learned anything from the new Kaminsky DNS attack, it's that if you want to keep something a secret while disclosing to a trusted subset of…

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