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

Array#keep_if

array.keep_if {|element| ... } → self
array.keep_if → new_enumeration

Retains those elements for which the block returns a truthy value; deletes all other elements; returns self:

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

Returns a new Enumerator if no block given:

Example
a = [:foo, 'bar', 2, :bam]
a.keep_if # => #<Enumerator: [:foo, "bar", 2, :bam]:keep_if>
See also #join #last #intersection #length also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1