Sometime we need to cleanup a hash based for nil values. If you're using Rails/ActiveSupport it's really easy. From Ruby 2.4 is method is supported natively.

hash = {a: true, b: false, c: nil, d: 'string'}
hash.compact
# => {:a=>true, :b=>false, :d=>"string"}

Pure Ruby counterpart for older rubies:

hash = {a: true, b: false, c: nil, d: 'string'}
hash.reject {|_, v| v.nil?}
# => {:a=>true, :b=>false, :d=>"string"}

Pure Ruby counterpart for older rubies of compact!:

hash = {a: true, b: false, c: nil, d: 'string'}
hash.delete_if {|_, v| v.nil?}
# => {:a=>true, :b=>false, :d=>"string"}



What's on your mind?