Open In App

How to Add Key and Value to Hash in Ruby?

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Hashes is one of the most important data structures in Ruby. In this article, we will learn how to add keys and values to hash in Ruby. We will discuss various approaches to adding key-value pairs to a hash in Ruby.

Prerequisites

Before learning how to add key-value pairs to hashes in Ruby, we should have:

  1. Ruby is installed in our system, if not installed then download it from Ruby's official website
  2. Basic knowledge of Ruby programming

What is Hash?

A hash is a collection of unique keys and their associated values pair. In Ruby, hashes are created using curly braces {} with key-value pairs separated by commas. They are similar to arrays, but they use keys as numerical indices to access elements.

Creating Hashes

1. Creating an Empty Hash

We can create an empty hash using curly braces {} or the Hash.new method.

Syntax:

# Creating an empty hash using curly braces

hash = {}

# Creating an empty hash using the Hash.new method

hash = Hash.new

2. Creating a Hash with Initial Values

We can create hash with initial key-value pairs.

Syntax:

# Creating a hash with initial values

hash = { "name" => "geek", :age => 20, "city" => "Noida" }


Accessing Hash Values

To access the values in a hash, use the keys:

Ruby
person = { "name" => "Geeks", "age" => 20, "city" => "New Delhi" }
puts person["name"]  
puts person["age"]   

Output
Geeks
20

Adding Key-Value Pairs to Hashes

1. Using Hash Literal Syntax

We can add key-value pairs to an existing hash using the hash literal syntax.

Below is the Ruby program to add key-value pair to hashes using hash literal syntax:

Ruby
person = { "name" => "Geeks" }
person["age"] = 20
person["city"] = "New Delhi"

puts person

Output
{"name"=>"Geeks", "age"=>20, "city"=>"New Delhi"}

2. Using the []= Method

The []= method allows us to add or update key-value pairs.

Below is the Ruby program to add key-value pair to hashes using the []= Method:

Ruby
person = { "name" => "Geeks" }
person["age"] = 20

puts person

Output
{"name"=>"Geeks", "age"=>20}

3. Adding Multiple Key-Value Pairs

To add multiple key-value pairs at once, we can use the merge! method.

Below is the Ruby program to add multiple key-value pair to hashes:

Ruby
person = { "name" => "Geekina" }
person.merge!({ "age" => 20, "city" => "New Delhi" })

puts person

Output
{"name"=>"Geekina", "age"=>20, "city"=>"New Delhi"}

4. Adding Keys with Computed Values

We can compute values before adding them to the hash.

Below is the Ruby program to add keys to computed values:

Ruby
person = { "name" => "Geeks" }
person["age"] = 10 + 10

puts person

Output
{"name"=>"Geeks", "age"=>20}

5. Using Symbols as Keys

Symbols are often used as keys in Ruby hashes because they are more efficient than strings.

Below is the Ruby program to use symbol as keys:

Ruby
person = { name: "Geekina", age: 20, city: "New Delhi" }

puts person

Output
{:name=>"Geekina", :age=>20, :city=>"New Delhi"}

6. Working with Nested Hashes

Hashes can contain other hashes as values, creating a nested structure.

Below is the Ruby program to implement nested hashes:

Ruby
person = { name: "Geeks", details: { age: 20, city: "New Delhi" } }
person[:details][:country] = "India"

puts person

Output
{:name=>"Geeks", :details=>{:age=>20, :city=>"New Delhi", :country=>"India"}}

Updating Existing Keys

1. Modifying Values for Existing Keys

To update the value of an existing key, simply assign a new value to the key.

Below is the Ruby program to modify values for existing keys:

Ruby
person = { "name" => "Geekina", "age" => 20 }
person["age"] = 21

puts person

Output
{"name"=>"Geekina", "age"=>21}

2. Merging Hashes

The merge method combines two hashes, returning a new hash.

Below is the Ruby program to merge hashes:

Ruby
person = { "name" => "Geek", "age" => 20 }
additional_info = { "city" => "New Delhi", "country" => "India" }
updated_person = person.merge(additional_info)

puts updated_person

Output
{"name"=>"Geek", "age"=>20, "city"=>"New Delhi", "country"=>"India"}

3. Using merge! for In-Place Updates

The merge! method updates the original hash in place.

Below is the Ruby program to use merge! for in-place updates:

Ruby
person = { "name" => "Geekina", "age" => 20 }
person.merge!({ "city" => "New Delhi", "country" => "India" })

puts person

Output
{"name"=>"Geekina", "age"=>20, "city"=>"New Delhi", "country"=>"India"}

Conditional Key-Value Addition

1. Adding Key-Value Pairs Conditionally

We can add key-value pairs based on certain conditions.

Below is the Ruby program to add key-value pairs conditionally:

Ruby
person = { "name" => "Geeks", "age" => 20 }
person["city"] = "New Delhi" unless person.key?("city")

puts person

Output
{"name"=>"Geeks", "age"=>20, "city"=>"New Delhi"}

2. Using Hash#fetch with Default Values

The fetch method can provide default values if a key is not found:

Below is the Ruby program to use hash#fetch with default values:

Ruby
person = { "name" => "Geeks" }
age = person.fetch("age", 20)

puts age

Output
20

Conclusion

In Ruby, we have seen various methods for adding key-value pairs to a has. Each method has its advantages and use cases. Bracket notation and the store method are straightforward for single pair insertions and updates, while merge and update are powerful for handling multiple pairs and combining hashes. Each method are used in various cases according to its advantage.


Next Article
Article Tags :

Similar Reads