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
array.c
View on GitHub ↗
static VALUE
rb_ary_keep_if(VALUE ary)
{
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
rb_ary_select_bang(ary);
return ary;
}
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>