The task is simple - I have a string like "I don't know"
and I want substitute '
with \'
(I know that I don't have to escape single quotes). How can I do it?
Asked
Active
Viewed 157 times
1

Bohdan
- 8,298
- 6
- 41
- 51
-
Similar [Escape doube and single backslashes in a string in Ruby](http://stackoverflow.com/questions/2774808/escape-doube-and-single-backslashes-in-a-string-in-ruby) – chown Nov 10 '11 at 14:41
-
@chown: nah, this problem is about how gsub interprets the special match variables with an escape prefix in the replacement string. – maerics Nov 10 '11 at 14:50
-
@maerics Yea, probably not a duplicate, but *similar*. – chown Nov 10 '11 at 15:23
1 Answers
2
Try using the block form, it should work in all versions of Ruby:
s.gsub(/'/) {"\\'"}
# => "I don\\'t know"
[Edit]
The reason is that the gsub
method has special handling for backslash sequences in the replacement string which correspond to the special match variables. So you can use $'
(and $1
, etc.) directly in the substituted string by using the form \\'
(and \\1
, etc.) instead.
The block form of gsub doesn't have this behavior, so that's the workaround when you're trying to sub in a string that looks like a special backslash sequence.

maerics
- 151,642
- 46
- 269
- 291
-
Also `s.gsub(/'/,'\\\\\'')` or `s.gsub(/'/, "\\\\'")`. But @maerics is clearer. – Zabba Nov 10 '11 at 14:40
-
I guess it somehow matches `$'` value when you do `s.gsub(/'/,"\\'")` right? – Bohdan Nov 10 '11 at 14:41
-
@Bohdan: right, in the replacement string you can use some of the special match variables (e.g. `$'`, `$1`) by using the escaped form (`\\'`, `\\1`) but the block form of gsub doesn't have this "convenience" =) – maerics Nov 10 '11 at 14:45