Substituting single quotes in strings

Hi

I want to substitute single quotes in a string but fails unless resorting to overkill (imho) techniques like blocks:

s = "ab'cd"

=> "ab'cd"

s.sub("'") {|s| %q{\'} }

=> "ab\\'cd"

As seen this method works but why can't I do something like

a.sub("'", %q{\'})

=> "aaabbbbbb"

when

a.sub("'", %q{h})

=> "aaahbbb"

works?

Can someone shed some light on this? Thanks in advance.

Regards

Erik

Hi

I want to substitute single quotes in a string but fails unless resorting to overkill (imho) techniques like blocks:

s = "ab'cd"

=> "ab'cd"

s.sub("'") {|s| %q{\'} }

=> "ab\\'cd"

s.sub("'","\\\\'")

You need four backslashes because: - backslashes have to be escaped in a string literal - in the case of a sub/gsub subsitution, a backslash has special
meaning (because you can do stuff like s.sub(/(')/, "x\\1x") #=>
"abx'xcd"

Fred

Thanks

I did not think about the potential back reference for regexps. Good catch.

Regards

Erik