Project

General

Profile

Actions

Feature #8853

open

Should String#sub(pattern) returns an Enumerator?

Added by okkez (okkez _) over 10 years ago. Updated over 4 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-dev:47688]

Description

調べてみたのですが、過去に同様の議論があったのかどうかわからなかったので起票します。

以下のように String#sub(pattern) と使うと ArgumentError が発生します。

$ ruby -e "p ''.sub(//)"
-e:1:in sub': wrong number of arguments (1 for 2) (ArgumentError) from -e:1:in '

一方、 String#gsub(pattern) だと Enumerator を返します。

$ ruby -e "p ''.gsub(//)"
#<Enumerator: "":gsub(//)>

RDoc ではこの挙動は説明されていませんでした。
String#gsub(pattern)がEnumeratorを返すことについては書かれています。
http://www.ruby-doc.org/core-2.0.0/String.html#method-i-sub
http://www.ruby-doc.org/core-2.0.0/String.html#method-i-gsub

一貫性の観点から考えると、String#sub(pattern)もEnumeratorを返した方が良いように思いましたがいかがでしょうか。
まあ、String#sub だと置換は一回しか発生しないのでイマイチな感じはします。

  • String#sub(pattern) が Enumerator を返すようになる
  • RDoc に String#gsub(pattern) と違って String#sub(pattern) が ArgumentError を発生させることの記述が追加される

のどちらかが、満たされればいいと思っています。


Files

string-sub-enumerator.patch (3.52 KB) string-sub-enumerator.patch jeremyevans0 (Jeremy Evans), 07/13/2019 12:30 AM

Updated by jeremyevans0 (Jeremy Evans) over 4 years ago

If I understand this correctly, this is a feature request to make String#sub and #sub! return an Enumerator if given a single argument and no block. I'm not sure how useful this would be. With #sub!, you can use the enumerator to mutate the string passing the replacement in via Enumerator#feed. However, with #sub, you cannot use the enumerator to modify anything, since the String#sub receiver is not modified, and you can't get access to the resulting string. However, assuming this is desired, the attached patch implements it.

Actions

Also available in: Atom PDF

Like0
Like0