0

Why does this happen?

irb(main):011:0> "\\\\".gsub("\\\\","\\")
=> "\\"

irb(main):012:0> "\\".gsub("\\","\\\\")
=> "\\"

Using jruby 1.7.21 if that matters (equivalent to ruby 1.9.3)

Edit: perhaps even more perplexingly...

irb(main):012:0> "\\".gsub("\\","\\\\\\")
=> "\\\\"
Karl
  • 6,035
  • 5
  • 30
  • 39
  • Nevermind, it's because of this: http://stackoverflow.com/questions/1542214/weird-backslash-substitution-in-ruby – Karl Jan 21 '16 at 01:18
  • 1
    That is odd. It must have something to do with gsub's paying attention to backslashes to parse `\1` references in the substitution string, it's getting confused with the backslashes. somehow telling gsub to replace with `'\\\\'` gets un-escaped twice. I'd think it is probably a bug, but hard to say, it is confusing dealing with backslashes in ruby string literals. – jrochkind Jan 21 '16 at 01:22
  • I don't actually understand the link you post to, I don't think it fully explains it. It IS true that the string literal `"\\"` is actually only one single character, one single byte, one backslash. `"\\".length == 1`. But that doesn't explain why `"\\".gsub("\\","\\\\") == "\\"`. That should, I would think, say to replace one backslash with two, but it replaced it with one instead. What happened to the other backslash? Something odd is going on. – jrochkind Jan 21 '16 at 01:25
  • @jrochkind Look at Peter's answers at the bottom of the duplicate, not exactly detailed but they do cover this. – mu is too short Jan 21 '16 at 01:39
  • Ah, I do see, thanks. The answer from two-bit-fool with the most votes is a pretty good answer. I got distracted by the accepted answer, which is a terrible non-answer with some misleading information. – jrochkind Jan 21 '16 at 13:14

0 Answers0