Forum: Ruby on Rails Substituting single quotes in strings

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4a7a142aab3340704a9ae1abe74a3263?d=identicon&s=25 Erik Lindblad (Guest)
on 2008-12-16 16:01
(Received via mailing list)
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
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-12-16 17:06
(Received via mailing list)
On 16 Dec 2008, at 15:01, Erik Lindblad 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
4a7a142aab3340704a9ae1abe74a3263?d=identicon&s=25 Erik Lindblad (Guest)
on 2008-12-16 17:39
(Received via mailing list)
Thanks

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

Regards

Erik
This topic is locked and can not be replied to.