[ruby-core:94235] [Ruby master Bug#16091] gsub
From:
merch-redmine@...
Date:
2019-08-09 22:59:53 UTC
List:
ruby-core #94235
Issue #16091 has been updated by jeremyevans0 (Jeremy Evans).
Status changed from Feedback to Rejected
This is not a bug. Ruby treats `\&` in a replacement string specially, representing the entire matched string (note that `"\\&"` is the same as `'\&'`):
```ruby
"test ?".sub("?", "1\\&2")
=> "test 1?2"
```
So `"\\&"` as a replacement string means perform the replacement, but use the same text as what you are replacing.
If you want to replace something with `\&`, you need to double the backslashes:
```ruby
puts "test ?".sub("?", "\\\\&")
# output: test \&
```
If you want to replace something with `&`, use no backslashes:
```ruby
puts "test ?".sub("?", '&')
# output: test &
```
Python does not handle `\&` specially, which is why the behavior is different.
----------------------------------------
Bug #16091: gsub
https://bugs.ruby-lang.org/issues/16091#change-80541
* Author: thiaguerd (thiago feitosa)
* Status: Rejected
* Priority: Normal
* Assignee:
* Target version:
* ruby -v: 2.6.2p47 (2019-03-13 revision 67232) [x86_64-linux]
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN
----------------------------------------
```ruby
a = "test ?"
b = "?"
c = "\\&"
a.gsub(b,c)
```
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>