Adding or Removing Operations in Hashes
Adding a value to existing has can add new key-value pair or will replace existing key-value pair if adding to existing has key-value pair with the same key.
my_hash = {}
my_hash[“one”] = 1
If you use string as your hash key, then this key copy is frozen. It means that this key cannot be modified and if you try to do so via my_hash.keys[0].downcase! you will get an error stating: “Can’t modify frozen string”
You can employ merge method of Hash class if you want to combine two hashes together. You can do it via my_hash1.merge!( my_hash2). Note: hash key from my_hash2 will take precedence over my_hash1 if key is the same. If you want to create an brand new hash out of two then use same merge method without an exclamation point: my_hash1.merge( my_hash2)
In case, you want to replace content of one hash with another you can employ replace method of Hash class: my_hash1.repalce( my_hash2)
Removing an element of the hash is not difficult and is usually done via call to delete methods of Hash class.
my_hash1.delete(one)
You should use hash iterator if you want to delete more than one key-value pair from the hash. In order to accomplish this, you need to use delete_if iterator as implemented in the Hash class.
delete_if { |key,value| value == my_value }
Finally, there is a method called clear that will wipe out your hash completely.
my_hash.clear
Side note: in order to check for any null key in the hash you can employ has_key? method of Hash class.