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.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…