This project is closed and read-only.
Bug #1443
closedString#gsub handles backslashes incorrectly
Description
=begin
@shyouhei (Shyouhei Urabe) Urabe
I didn't see how to comment on the bug so i hid to file a new one
This is a continuation of bug #1441
The backslashes are being doubled under single quotes and double quotes, but String#gsub requires you to quadruple (4x) them, 4 backslashes for every one in the resultant string.
printf "b".gsub("b","\\")
prints a single backslash(), while it should print 2(\). (as printf "\\"; does)
The reason it looks different is because String#inspect shows strings as escaped.
=end
Updated by matz (Yukihiro Matsumoto) over 17 years ago
=begin
Hi,
In message "Re: [ruby-core:23389] [Bug #1443] String#gsub handles backslashes incorrectly"
on Thu, 7 May 2009 22:00:03 +0900, shawn landen redmine@ruby-lang.org writes:
|This is a continuation of bug #1441
|
|The backslashes are being doubled under single quotes and double quotes, but String#gsub requires you to quadruple (4x) them, 4 backslashes for every one in the resultant string.
|
|printf "b".gsub("b","\\")
Backslashes have special escape meaning in strings, so you need to
double slashes. In addition, backslashes have special meaning in
gsub/sub replacement strings, so you need to double again. That is
the reason you need 4 backslashes for each single backslash in a
replacement. It's weird but it's spec for long time. I don't think
we can change this behavior. You can use block instead, e.g.
printf "b".gsub(/b/){'\'}
=end
Updated by matz (Yukihiro Matsumoto) over 17 years ago
- Status changed from Open to Rejected
=begin
=end
Updated by moxley (Moxley Stratton) almost 15 years ago
puts "\"
\
puts "s".gsub("s", "\")
\
puts "\\"
\
puts "s".gsub("s", "\\")
\
gsub() returns inconsistent results. It should not modify the replacement string value.
string = File.read(some_file_with_backslashes_in_it)
string = "s".gsub("s", File.read(some_file_with_backslashes_in_it))
The above two examples should give the same result, but they don't. The file content has been modified by gsub(). It should not be modified.
This is not an issue with Ruby string literal syntax. It is an issue with gsub() and sub() methods.
Updated by now (Nikolai Weibull) almost 15 years ago
On Wed, Oct 12, 2011 at 19:38, Moxley Stratton
moxley.stratton@gmail.com wrote:
puts "\"
\
puts "s".gsub("s", "\")
\
There’s nothing to escape, thus “\”.
puts "s".gsub("s", "\\")
\
There’s a backslash to escape, thus “\”.
Updated by moxley (Moxley Stratton) almost 15 years ago
I understand now.
The replacement string value is parsed for pattern group references, such as \1.
http://redmine.ruby-lang.org/issues/1251
Thank you
Updated by moxley (Moxley Stratton) almost 15 years ago
I will use String#[]= instead:
string['pattern'] = File.read(some_file_with_backslashes_in_it)
This meets my requirements.