Hugh Sasse wrote:
> On Fri, 24 Nov 2006, Jeremy Wells wrote:
>
> [...]
>> original_section = $1
>> new_section = bit_at_top + original_section
>> new_body = body.sub(original_section, new_section)
> new_body = body.sub(Regexp.new(Regexp.quote(original_section) ),
> new_section)
>>
>> File.open(input,'w') do |file|
>> file.write new_body
>> end
>> end
>
> # Hugh
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\\\\\\\\\\\\\\\\KJahfd kasjhdfkajshdfjh\nsection
footer"
irb(main):062:0> y
=> "\nkjhKAJSHDKjashdkjASH\\\\\\\\\\\\\\\\KJahfdkasjh dfkajshdfjh\n"
irb(main):063:0> z
=> "xyzzy
\nkjhKAJSHDKjashdkjASH\\\\\\\\\\\\\\\\KJahfdkasjhd fkajshdfjh\n"
irb(main):064:0> x.sub(y,z)
=> "section headerxyzzy
\nkjhKAJSHDKjashdkjASH\\\\\\\\KJahfdkasjhdfkajshdf jh\nsection footer"
irb(main):065:0> x.sub(Regexp.new(Regexp.quote(y)),z)
=> "section headerxyzzy
\nkjhKAJSHDKjashdkjASH\\\\\\\\KJahfdkasjhdfkajshdf jh\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}
--
Posted via
http://www.ruby-forum.com/.