End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Hash#keep_if
hash.keep_if {|key, value| ... } → self
hash.keep_if → new_enumerator
hash.c
View on GitHub ↗
static VALUE
rb_hash_keep_if(VALUE hash)
{
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
rb_hash_modify_check(hash);
if (!RHASH_TABLE_EMPTY_P(hash)) {
rb_hash_foreach(hash, keep_if_i, hash);
}
return hash;
}
Calls the block for each key-value pair; retains the entry if the block returns a truthy value; otherwise deletes the entry; returns self.
Example
h = {foo: 0, bar: 1, baz: 2} h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
Returns a new Enumerator if no block given:
Example
h = {foo: 0, bar: 1, baz: 2} e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if> e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}