Project

General

Profile

Bug #11793

puts 'ab'.gsub('a', '\\+') - unexpected output

Added by burnson (William Burnson) almost 4 years ago. Updated almost 4 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]
[ruby-core:71976]

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

History

Updated by burnson (William Burnson) almost 4 years ago

  • Description updated (diff)

Updated by burnson (William Burnson) almost 4 years ago

  • Description updated (diff)

Updated by burnson (William Burnson) almost 4 years ago

  • Description updated (diff)

Updated by burnson (William Burnson) almost 4 years ago

  • Description updated (diff)

Updated by Hanmac (Hans Mackowiak) almost 4 years ago

its because how gsub works you need to escape the \

puts 'ab'.gsub('a', '\\\+') #=> \+b

Updated by usa (Usaku NAKAMURA) almost 4 years ago

  • Status changed from Open to Rejected

Updated by phluid61 (Matthew Kerwin) almost 4 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) almost 4 years ago

I should have used this example:

puts 'ab'.gsub('a', "\x5C\x5C\x2B")
\+b

Updated by nobu (Nobuyoshi Nakada) almost 4 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.

Also available in: Atom PDF