Bug #8511

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

Added by galnaktar (Oleg K) over 7 years ago. Updated over 7 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("...", "\\\")
=> "\\"

Updated by nobu (Nobuyoshi Nakada) over 7 years ago

  • Status changed from Open to Rejected

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

Updated by galnaktar (Oleg K) over 7 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 ...

Updated by galnaktar (Oleg K) over 7 years ago

Should I open new bug?

Updated by drbrain (Eric Hodel) over 7 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