views:

89

answers:

5

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?

A: 

How about doing this :

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

Not pretty but I think it works...

marcgg
The destructive version doesn't work either. just gives back a blank string from the irb prompt
Earlz
Ok let me take a look at it
marcgg
Ruby version is `ruby 1.8.6 (2009-06-08 patchlevel 369) [x86_64-openbsd4.6]`
Earlz
A: 

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"
Trevoke
Yes, this is not making sense to me.. sure I could use regex for it, but that seems like overkill.
Earlz
+2  A: 

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
FM
+6  A: 

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.

Jonas Elfström
Thanks for explaining that for me.. I guess gsub just has some hidden "features"
Earlz
A: 

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...

Torbjørn