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

On 16 Dec 2008, at 15:01, Erik L. wrote:

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs