Skip to content

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

instance method

Hash#compact

() -> ::Hash[K, V]
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.3 · 3.2 · 3.1 · 3.0