How to remove a key from a hash?

How to remove a key from a hash?

The most common way to remove a key from a Hash in Ruby is to use the delete method:

hash = { :a => 1, :b => 2, :c => 3 }
hash.delete(:b) # => 2
hash # => { :a => 1, :c => 3 }

If you need to remove multiple keys from a Hash, you can use the delete_if method:

hash = { :a => 1, :b => 2, :c => 3 }
hash.delete_if { |key, value| key == :a || key == :b } # => { :c => 3 }

If you need to remove all keys from a Hash, you can use the clear method:

hash = { :a => 1, :b => 2, :c => 3 }
hash.clear # => {}
2 Likes

You can also do:

hash = { :a => 1, :b => 2, :c => 3 }
hash.reject { |key, value| key == :b }
hash # => { :a => 1, :c => 3 }

In case you’re using Rails, you can also do:

hash = { :a => 1, :b => 2, :c => 3 }
hash.except(:c)
hash # => { :a => 1, :c => 3 }
1 Like

The difference between delete_if and reject is that delete_if modifies the hash object and reject creates a new one.

h = { a: 1, b: 2, c: 3 }      # => {:a=>1, :b=>2, :c=>3}
h.reject {|k, v| k == :b }    # => {:a=>1, :c=>3}
h                             # => {:a=>1, :b=>2, :c=>3}
h.delete_if {|k,v| k == :b }  # => {:a=>1, :c=>3}
h                             # => {:a=>1, :c=>3}
2 Likes