How to replace single quotes with escaped single quotes in ruby
escaping, gsub, regex, ruby
Solution
`String#gsub` in the form `gsub(exp,replacement)` has odd quirks affecting the replacement string which sometimes require lots of escaping slashes. Ruby users are frequently directed to use the block form instead:
str.gsub(/'/){ "\\'" }
If you want to do away with escaping altogether, consider using an alternate string literal form:
str.gsub(/'/){ %q(\') }
Once you get used to seeing these types of literals, using them to avoid escape sequences can make your code much more readable.
Problem
I'm trying to replace single quotes (') with escaped single quotes (\') in a string in ruby 1.9.3 and 1.8.7. The exact problem string is "Are you sure you want to delete '%@'". This string should become "Are you sure you want to delete \'%@\'" Using .gsub!(/\'/,"\'") leads to the following string "Are you sure you want to %@'%@". Any ideas on what's going on?