Question

I'm trying to figure out how to replace a quote like ' with something like \'.

How would I do this?

I have tried

"'".gsub("'","\\'")

but it just gives an empty string. What am I doing wrong here?

Was it helpful?

Solution

How about this

puts "'".gsub("'","\\\\'")
\'

The reason is that \' means post-match in gsub (regex) and because of that it needs to be escaped with \\' and \ is obviously escaped as \\, ending up with \\\\'.

Example

>> "abcd".gsub("a","\\'")
=> "bcdbcd"

a is replaced with everything after a.

OTHER TIPS

The $' variable is the string to the right of the match. In the gsub replacement string, the same variable would be \' -- hence the problem.

x = "'foo'"
x.gsub!(/'/, "\\'")
puts x.inspect        # foo'foo

This should work:

x = "'foo'"
x.gsub!(/'/, "\\\\'")
puts x.inspect
puts x

That might be a bug.. Or at the very least, something which breaks MY idea of the principle of least surprise.

irb(main):039:0> "life's grand".gsub "'", "\\\'"
=> "lifes grands grand"
irb(main):040:0> "life's grand".gsub "'", "\\\\'"
=> "life\\'s grand"

A two-step approach I've actually used...

BACKSLASH = 92.chr
temp = "'".gsub("'", "¤'")
puts temp.gsub("¤", BACKSLASH)
=> "\'"

Will only work if '¤' isn't used in the text obviously...

How about doing this :

"'".gsub("\\","\\\\\\\\").gsub("'","\\\\'")

Not pretty but I think it works...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top