On 16 Dec 2008, at 15:01, Erik Lindblad wrote:
>
> 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
> 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
>
> >
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---