HI,
In message "Re: [ruby-core:22715] [Bug #1251] gsub problem"
on Sat, 7 Mar 2009 18:08:11 +0900, Alexander Pettelkau <redmine / ruby-lang.org> writes:
|I wanted to replace "\" with "\\" in the string "\TEST":
|
|s="\\TEST"
|puts s # Output --> "\TEST"
|s.gsub!("\\","\\\\")
|puts s # Output --> "\TEST"
| # but EXPECTED Output "\\TEST"
You specified four backslashes in double quotes, which is two
backslashes in a string. But replacement character does backslash
escapement such as \1, and \\ (two backslashes) are transformed into
one backslash. That means you've substituted one backslash to one
backslash.
To substitute one backslash into two, you have to do
s.gsub!("\\","\\\\\\")
or
s.gsub!(/\\/){"\\\\"}
matz.