Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#filter

() { (Elem element) -> ::boolish } -> ::Array[Elem]
() -> ::Enumerator[Elem, ::Array[Elem]]
filter {|element| ... } → new_array
filter → new_enumerator

Alias of #select

With a block given, calls the block with each element of self; returns a new array containing those elements of self for which the block returns a truthy value:

Example
a = [:foo, 'bar', 2, :bam]
a.select {|element| element.to_s.start_with?('b') }
# => ["bar", :bam]

With no block given, returns a new Enumerator.

Related: see Methods for Fetching.

See also #select #filter! #fill #fetch_values also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0