While debugging some ruby grok bugs, I found something very strange where String#sub replaces all double backslashes with single backslashes
Input: hello world
Expected result: Hurray for slashes! \\testing//
Actual result: Hurray for slashes! \testing//
Equal: false
This is quite confusing. I said "replace this string with that string" and it took the 'that string' and replaced all double backslashes with single backslashes? This is very strange and certainly a bug.
This is probably an integration problem due to String#sub supporting captured groups when used with regexps; from the ruby docs - http://www.ruby-doc.org/core-1.9.3/String.html :
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.
I think this is a bug. If the first argument to String#sub() is a string, then there will be no capturing so there is no need to process backslashes and capture groups in the replacement string.
I can see why this is somewhat surprising, but it doesn't seem incorrect. It would be more surprising if it were inconsistent between the String case and the Regexp case, I think.
And @meineerde, per https://github.com/rubyspec/rubyspec/blob/master/core/string/sub_spec.rb#L274, it seems
\
sequences are indeed ignored for the block. Presumably this is because inside the block, you have$1
, etc available and don't need other special rules.