Bug #8511

gsub("\\","\\\\") works incorrect

Added by galnaktar (Oleg K) about 4 years ago. Updated about 4 years ago.

Target version:
ruby -v:
ruby 2.0.0p195 (2013-05-14) [i386-mingw32]


DL is deprecated, please use Fiddle
irb(main):001:0> a = "\"
=> "\"
irb(main):002:0> a.gsub("\", "\\")
=> "\"
irb(main):003:0> a.gsub("\", ".")
=> "."
irb(main):004:0> a.gsub(".", "\\")
=> "\"
irb(main):005:0> a = "\"
=> "\"
irb(main):006:0> a.gsub("..", "\\")
=> "\"
irb(main):007:0> a.gsub("..", "\\")
=> "\"
irb(main):008:0> "\".gsub("..", "\\")
=> "\"
irb(main):009:0> "\".gsub(/./, "\\")
=> "\"
irb(main):010:0> "..".gsub("..", "\\")
=> "\"
irb(main):011:0> "...".gsub("...", "\\\")
=> "\\"


#1 [ruby-core:55426] Updated by nobu (Nobuyoshi Nakada) about 4 years ago

  • Status changed from Open to Rejected

I'm not sure what you expect, it works as expected.

#2 [ruby-core:55427] Updated by galnaktar (Oleg K) about 4 years ago

nobu (Nobuyoshi Nakada) wrote:

I'm not sure what you expect, it works as expected.

irb(main):005:0> "\".gsub("\", "\\").length
=> 1
irb(main):006:0> "\".gsub("\", "XX").length
=> 2

I thought that the length must return 2 in both cases ...

#3 [ruby-core:55429] Updated by galnaktar (Oleg K) about 4 years ago

Should I open new bug?

#4 [ruby-core:55445] Updated by drbrain (Eric Hodel) about 4 years ago

No, it works as expected, please read the documentation for String#gsub:

If replacement is a String it will be substituted for the
matched text. It may contain back-references to the pattern's capture groups
of the form \\d, where d is a group number, or \\k,
where n is a group name. If it is a double-quoted string, both
back-references must be preceded by an additional backslash. However, within
replacement the special match variables, such as $&, will not
refer to the current match.

So your replacement string (({"\\"})) replaces with one backslash, not two. Use:

"\".gsub("\", "\\\\") #=> "\\" (length 2)


Also available in: Atom PDF