Bug #8511

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

Added by Oleg K 11 months ago. Updated 11 months ago.

[ruby-core:55425]
Status:Rejected
Priority:Normal
Assignee:-
Category:-
Target version:-
ruby -v:ruby 2.0.0p195 (2013-05-14) [i386-mingw32] Backport:1.9.3: UNKNOWN, 2.0.0: UNKNOWN

Description

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("...", "\\\")
=> "\\"
irb(main):012:0>

History

#1 Updated by Nobuyoshi Nakada 11 months ago

  • Status changed from Open to Rejected

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

#2 Updated by Oleg K 11 months 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 Updated by Oleg K 11 months ago

Should I open new bug?

#4 Updated by Eric Hodel 11 months ago

=begin
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)

=end

Also available in: Atom PDF