Issue #17184 has been updated by Eregon (Benoit Daloze).


@chrisseaton noticed the same issue a while ago.

`String#[]=` only replaces the first occurrence (and mutates the receiver).

I think we should remove special treatment of `\+`, etc in the replacement string for `sub/gsub(String, String)`.
There is no Regexp involved, so I think there is no reason to have those Regexp backreferences.
`sub/gsub(String, String)` only has a single "group", which is 0 and exactly the same as the replacement String, so those backreferences seem useless.

Here is the list of those special `\` sequences:
https://github.com/oracle/truffleruby/blob/6bb23e236f83416fc4a000b6f3cf976947117ed7/src/main/ruby/truffleruby/core/truffle/string_operations.rb#L187-L246

Potentially incompatible, but who would use those sequences for `sub/gsub(String, String)`?
I think it's always unintentional, and a source of subtle bugs.

And worse than that, I can imagine it could become a security issue if the pattern String is fixed and the replacement String comes from user input.
Then the user would expect the pattern String cannot be seen in the result, but it can if the replacement String is `\&`.

@sheerun I'd suggest to not bother with a capacity computation, that's very unidiomatic. You can use `new_str = str.dup` instead.

----------------------------------------
Bug #17184: No stdlib function to perform simple string replacement
https://bugs.ruby-lang.org/issues/17184#change-87674

* Author: sheerun (Adam Stankiewicz)
* Status: Open
* Priority: Normal
* ruby -v: ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-darwin19]
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN
----------------------------------------
I have following simple `build.rb`:

```rb
template = File.read('template.vim')
script = File.read('script.vim')
File.write('app.vim', template.gsub("SCRIPT", script))
```

And then following `template.vim`:

```vim
" some header
SCRIPT
```

Plus following `script.vim`:


```vim
if g:something =~ "\s\+"
  echo 'g:something is empty'
endif
```

I'd expect that the script above produces `app.vim` with following contents:

```vim
" some header
if g:something =~ "\s\+"
  echo 'g:something is empty'
endif
```

Unfortunately it produces following:

```vim
" some header
if g:something =~ "\s"
  echo 'g:something is empty'
endif
```

It's probably because gsub interprets `\+` in script as back-reference.

I tried to find replacement function in ruby that just replaces one string with something else, without interpreting replacement in any way, but surprisingly I haven't found any.. Am I mistaken?




-- 
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>