"Simon Strandgaard" <neoneye / adslhome.dk> schrieb im Newsbeitrag news:20040531140023.1c0d4fe9.neoneye / adslhome.dk... > "Robert Klemme" <bob.news / gmx.net> wrote: > > "Simon Strandgaard" <neoneye / adslhome.dk> schrieb im Newsbeitrag > > > > > > puts "hello".gsub!(/h/) {|m| "\\'"} > > > > Or > > > > >> puts "hello".gsub!(/h/, %q{\\\\'}) > > \'ello > > > > Note: > > > > >> puts %q{\\\\'} > > \\' > > > > > > You need an escaped backslash to prevent interpretation of it in the > > replacement pattern. > > I remember when I switched to Ruby, I had difficulties understanding > the escaping rules in conjunction with single/double quotes. > String#gsub got me really confused. It took some time for me, too. > I think I read somewhere that perl6 uses $ in the regexp replacement string, > in order to avoid our escaping hell. I think this is a good initiative. > So escape can be used freely: > "hello".gsub!(/h/, %q|\'|) #-> \'ello > "hello".gsub!(/(.)$1/, '$&$1') #-> helllo > > Maybe we should do an RCR.. use dollar in regexp? IMHO that would break too much code. After all quoting rules are very logical: Step 1: "" and '' quoting rules apply. Step 2: Then the gsub quoting rules apply to the result of step 1. IMHO confusion often results from testing in irb which will print an escaping backslash before each backslash in a string thus irritating people about the contents of the string printed: >> a=%q{\\} => "\\" >> puts a \ => nil Another source of confusion is the lax treatment of backslashes: >> a=%q{\1} => "\\1" >> puts a \1 => nil >> a=%q{\\1} => "\\1" >> puts a \1 => nil Normally you would have to use the second form only, that would be more logical IMHO. Regards robert