Skip to content

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

instance method

Enumerable#filter

filter

Alias of #find_all

Returns an array containing elements selected by the block.

With a block given, calls the block with successive elements; returns an array of those elements for which the block returns a truthy value:

Example
(0..9).select {|element| element % 3 == 0 } # => [0, 3, 6, 9]
a = {foo: 0, bar: 1, baz: 2}.select {|key, value| key.start_with?('b') }
a # => {:bar=>1, :baz=>2}

With no block given, returns an Enumerator.

Related: reject.

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