Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Hash#keep_if

hash.keep_if {|key, value| ... } → self
hash.keep_if → new_enumerator

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}
See also #invert #key #inspect #key? also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0