Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#filter

enum.filter { |obj| block } → array
enum.filter → an_enumerator

Alias of #find_all

Returns an array containing all elements of enum for which the given block returns a true value.

The find_all and select methods are aliases. There is no performance benefit to either.

If no block is given, an Enumerator is returned instead.

Example
(1..10).find_all { |i|  i % 3 == 0 }   #=> [3, 6, 9]

[1,2,3,4,5].select { |num|  num.even?  }   #=> [2, 4]

[:foo, :bar].filter { |x| x == :foo }   #=> [:foo]

See also Enumerable#reject, Enumerable#grep.

See also #find_all #entries #filter_map #each_with_object also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1