Add an Item to a Ruby Hash

Nurudeen Ibrahim Jan 30, 2023 Feb 23, 2022
  1. Use the Square Bracket Notation [] to Add to Ruby Hash
  2. Use the merge Method to Add to Ruby Hash
Add an Item to a Ruby Hash

The best and the most common way of adding a new item to a Ruby hash is by using square bracket notation []. Another way is to use the merge method, which comes in handy when multiple items need to be added at once.

Use the Square Bracket Notation [] to Add to Ruby Hash

Example Code:

country_codes = {
  "Nigeria" => "NG",
  "United State" => "US"
}
country_codes["Canada"] = "CN"

puts country_codes

Output:

{"Nigeria"=>"NG", "United State"=>"US", "Canada"=>"CN"}

In the above code, we can add the country code for "Canada" into the hash by using the bracket notation [].

Use the merge Method to Add to Ruby Hash

The merge method is useful if you add multiple items at once.

Example Code:

country_codes = {
  "Nigeria" => "NG",
  "United State" => "US"
}

new_country_codes = country_codes.merge({"Canada" => "CN", "Ghana" => "GH"})

puts new_country_codes

Output:

{"Nigeria"=>"NG", "United State"=>"US", "Canada"=>"CN", "Ghana"=>"GH"}

If we want to update the content of the country_codes hash without re-assigning the merge result to another variable, we should add an exclamation point ! like merge!.

Example Code:

country_codes = {
  "Nigeria" => "NG",
  "United State" => "US"
}

country_codes.merge!({"Canada" => "CN", "Ghana" => "GH"})

puts country_codes

Output:

{"Nigeria"=>"NG", "United State"=>"US", "Canada"=>"CN", "Ghana"=>"GH"}

Related Article - Ruby Hash