views:

722

answers:

3

I want to insert backslash before apostrophe in "children's world" string. Is there a easy way to do it?

irb(main):035:0> s = "children's world"
=> "children's world"
irb(main):036:0> s.gsub('\'', '\\\'')
=> "childrens worlds world"
+1  A: 

Your problem is that the string "\'" is meaningful to gsub in a replacement string. In order to make it work the way you want, you have to use the block form.

s.gsub("'") {"\\'"}
Chuck
+3  A: 
>> puts s.gsub("'", "\\\\'")
children\'s world
Magnar
It gets children\\'s world.
Jirapong
No, it doesn't.
Magnar
+4  A: 

from ruby-doc.org about the replacement pattern for gsub:

the sequences \1, \2, and so on may be used to interpolate successive groups in the match

This includes the sequence \', which means "everything following what I matched".

Either "\\'" or '\\\'' will both produce \' (remember that \ has to be escaped in both double and single quoted strings, and that ' has to be escaped in single-quoted strings, so using single-quotes in this case actually makes things more verbose). E.g.:

puts "before*after".gsub("*", "\\'")
"beforeafterafter"

puts "before*after".gsub("*", '\\\'')
"beforeafterafter"

What you want gsub to see then is actually \\', which can be produced by both "\\\\'" and '\\\\\''. So:

puts s.gsub("'", "\\\\'")
children\'s world

puts s.gsub("'", '\\\\\'')
children\'s world

or if you have to do a lot with \ you could take advantage of the fact that when you use /.../ (or %r{...}) you don't have to double-escape the backslashes:

puts s.gsub("'", /\\'/.source)
children\'s world
Jordan Brough