Feature #14197

`Enumerable#{select,reject}` accept a pattern argument

Added by znz (Kazuhiro NISHIYAMA) 5 months ago. Updated 2 months ago.

Target version:


#all?, #any?, #none?, and #one? accept a pattern argument since 2.5.0.
But #select, and #reject don't.

The features are exist as #grep, and #grep_v, but there are hard to remember for me when I use #select, or #reject.

So I want to write


instead of

collection.reject {|item| /re/ =~ item }



Related issues

Related to Ruby trunk - Feature #11286: [PATCH] Add case equality arity to Enumerable's sequence predicates.Closed


#1 Updated by znz (Kazuhiro NISHIYAMA) 5 months ago

  • Related to Feature #11286: [PATCH] Add case equality arity to Enumerable's sequence predicates. added

#2 [ruby-core:84379] Updated by shevegen (Robert A. Heiler) 5 months ago

I think this suggestion looks ok, unless I may have missed something.

The main difference Kazuhiro is suggesting, appears to be the shorter
notation via regex given to .reject() rather than use the (longer)
block variant.

Here is the link to #grep:

which shows one example:

c = IO.constants
c.grep(/SEEK/)         #=> [:SEEK_SET, :SEEK_CUR, :SEEK_END]

On a side note, while I have used .grep(), I have never used .grep_v()
and it is a bit mysterious to me what grep_v does from the name
alone. :)

#3 Updated by naruse (Yui NARUSE) 5 months ago

  • Target version deleted (2.6)

#4 [ruby-core:84840] Updated by inopinatus (Joshua GOODALL) 5 months ago

I have personally found it useful to implement Regexp#to_proc as in which permits collection.reject(&/re/) and more besides.

#5 [ruby-core:86247] Updated by xavriley (Xavier Riley) 2 months ago

This issue is also related

One interesting point there is the case where a pattern and a block are given:

%w{ant bear cat}.select(/bear/) {||x| x === "cat" }

This issue also applies to the implementation from the linked issue for #all?(pattern)but this is already implemented

>> %w{ant bear cat}.all?(String) {|x| x === Integer }
=> true

#6 [ruby-core:86248] Updated by matz (Yukihiro Matsumoto) 2 months ago

The point is that the phrase "hard to remember" in the OP is bit weak when we already have methods with the proposed behavior (grep and grep_v).


Also available in: Atom PDF