Bug #11793
closedputs 'ab'.gsub('a', '\\+') - unexpected output
Description
Test case:
puts 'ab'.gsub('a', '\\+')
Expected output:
\+b
Actual output:
b
The way I understand gsub(pattern, replacement)
when used with two string arguments is that it will perform a literal replacement, so it is quite unexpected that substituting with \+
removes the pattern entirely.
Doc: http://ruby-doc.org/core-2.2.3/String.html#method-i-gsub
Updated by burnson (William Burnson) over 8 years ago
- Description updated (diff)
Updated by burnson (William Burnson) over 8 years ago
- Description updated (diff)
Updated by burnson (William Burnson) over 8 years ago
- Description updated (diff)
Updated by burnson (William Burnson) over 8 years ago
- Description updated (diff)
Updated by Hanmac (Hans Mackowiak) over 8 years ago
its because how gsub
works you need to escape the \
puts 'ab'.gsub('a', '\\\+') #=> \+b
Updated by usa (Usaku NAKAMURA) over 8 years ago
- Status changed from Open to Rejected
Updated by phluid61 (Matthew Kerwin) over 8 years ago
Substitution parameters work in string-string mode:
irb> puts 'ab'.gsub('a', %q(\`))
b
irb> puts 'ab'.gsub('a', %q(\&))
ab
irb> puts 'ab'.gsub('a', %q(\'))
bb
irb> puts 'ab'.gsub('a', %q(\0))
ab
irb> puts 'ab'.gsub('a', %q(\\0))
ab
irb> puts 'ab'.gsub('a', %q(\\\0))
\0b
irb> puts 'ab'.gsub('a', %q(\\\+))
\+b
I used %q()
to make it clear just how many blackslashes are involved.
Note with the \0
examples, either a single or double-backslash invokes the special value replacement.
The plus symbol ($+
or \+
) is an alias for the $LAST_PAREN_MATCH
special value, which in this case is blank.
Updated by phluid61 (Matthew Kerwin) over 8 years ago
I should have used this example:
puts 'ab'.gsub('a', "\x5C\x5C\x2B")
\+b
Updated by nobu (Nobuyoshi Nakada) over 8 years ago
- Description updated (diff)
The document states "It may contain back-references", \+
is one of them.
Note: preformated text requires a preceding blank line.