Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Hash#compact

hash.compact → new_hash

Returns a copy of self with all nil-valued entries removed:

Example
h = {foo: 0, bar: nil, baz: 2, bat: nil}
h1 = h.compact
h1 # => {:foo=>0, :baz=>2}
See also #compact! #clear #assoc #compare_by_identity also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0