On 23.11.2006 19:50, Jeremy Wells wrote:
> 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

Frankly, I don't understand why everybody is trying to fix backslashes 
in replacement strings when there is gsub and grouping.  It's easier and 
more robust if you use grouping and use those groups in the replacement. 
  No problems with slashes in there (see my other posting).

Cheers

	robert