0

I want to escape single quotes using ruby #gsub but I observe strange behavior.

"My 'message'".gsub("'", "\\'")
-> "My message'message"

I expected to get "My \'message\'". Why is message repeated?

I can workaround that using "My 'message'".gsub("'") { "\\'" } but I'd like to know what happens with "My 'message'".gsub("'", "\\'").

cbliard
  • 7,051
  • 5
  • 41
  • 47
  • http://stackoverflow.com/questions/2180322/ruby-gsub-doesnt-escape-single-quotes has the answer: "\' means $' which is everything after the match.". What should I do with this question, should I delete it? – cbliard Dec 10 '15 at 08:27
  • I'd leave it alone now that it is marked as a duplicate. This particular problem is really hard to search for so maybe a duplicate will make the searching easier. – mu is too short Dec 10 '15 at 08:36
  • @muistooshort Ok, I'll not delete this question then. Thanks. – cbliard Dec 10 '15 at 08:38
  • _Sidenote_: since it’s 2015 all around, one might use typograhically correct single quotes `‘` and `’` instead of escaping apostrophs. – Aleksei Matiushkin Dec 10 '15 at 08:58
  • 1
    @mudasobwa tell that to our customers :) – cbliard Dec 10 '15 at 10:03

0 Answers0