From: Jeremy Wells Date: 2006-11-24T03:50:00+09:00 Subject: Re: double-slashes in input causing trouble Edwin Fine wrote: > Makes no difference. String#sub states that metacharacters in the > pattern will not be interpreted if the pattern is a String and not a > Regexp. > > Check it out: > > irb(main):061:0> x > => "section > header\nkjhKAJSHDKjashdkjASH\\\\\\\\\\\\\\\\KJahfdkasjhdfkajshdfjh\nsection > footer" > irb(main):062:0> y > => "\nkjhKAJSHDKjashdkjASH\\\\\\\\\\\\\\\\KJahfdkasjhdfkajshdfjh\n" > irb(main):063:0> z > => "xyzzy > \nkjhKAJSHDKjashdkjASH\\\\\\\\\\\\\\\\KJahfdkasjhdfkajshdfjh\n" > irb(main):064:0> x.sub(y,z) > => "section headerxyzzy > \nkjhKAJSHDKjashdkjASH\\\\\\\\KJahfdkasjhdfkajshdfjh\nsection footer" > irb(main):065:0> x.sub(Regexp.new(Regexp.quote(y)),z) > => "section headerxyzzy > \nkjhKAJSHDKjashdkjASH\\\\\\\\KJahfdkasjhdfkajshdfjh\nsection footer" > > Identical results. > > The problem is that the backslashes in the REPLACEMENT string are being > interpreted. > > The way to overcome this is to use the block form of sub: > > new_body = body.sub(original_section) {|s| s = new_section} > Thanks, I might try that, it's better looking than my solution, which was: m = Regexp.new("(" + Regexp.escape(original_section) + ")").match(body) body[(m.begin(1)..m.end(1)-1)] = new_section