Reputation: 51
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?
Upvotes: 3
Views: 7487
Reputation: 3703
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.
Upvotes: 8
Reputation: 46685
\'
in a substitution replacement string means "The portion of the original string after the match". So str.gsub!(/\'/,"\\'")
replaces the '
character with everything after it - which is what you've noticed.
You need to further escape the backslash in the replacement. .gsub(/'/,"\\\\'")
works in my irb
console:
irb(main):059:0> puts a.gsub(/'/,"\\\\'")
Are you sure you want to delete \'%@\'
Upvotes: 1
Reputation: 168269
You need to escape the backslash. What about this?
"Are you sure you want to delete '%@'".gsub(/(?=')/, "\\")
# => "Are you sure you want to delete \\'%@\\'"
The above should be what you want. Your expected result is wrong. There is no way to literally see a single backslash when it means literally a backslash.
Upvotes: 0