How to Add Key and Value to Hash in Ruby?
Last Updated :
05 Aug, 2024
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:
- Ruby is installed in our system, if not installed then download it from Ruby's official website
- 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"]
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
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.
Similar Reads
How to Sort a Hash in Ruby?
In this article, we will learn how to sort a Hash in ruby. We can sort the map by key, from low to high or high to low, using the sortBy method. Syntax:sorted_hash = original_hash.sort_by { |key, value| expression }.to_h Example 1: In this example, we sort a hash in ascending order [GFGTABS] Ruby #
2 min read
How to convert Array to Hash in Ruby?
In this article, we will discuss how to convert an array to a hash in Ruby. Converting an array to a hash can be useful when we have data in an array format and need to organize it into key-value pairs for easier access and manipulation. Table of Content Converting array to hash using Hash::[] const
3 min read
How to convert Hash to Object in Ruby?
In this article, we will discuss how to convert a hash to an object in Ruby. Converting hash to an object allows one to access hash keys as object attributes, providing them with a more intuitive way to work with data. Table of Content Using OpenStructUsing StructUsing Hash#eachUsing OpenStructOpenS
3 min read
How to Convert Hash to JSON in Ruby?
Ruby Hash is an unordered set of data in key-value pairs. These are mutable and can store multiple data types. JSON stands for Javascript Object Notation and is a human-readable file format that is commonly used in web services and API calls. In this article, we will discuss how to convert a hash to
2 min read
How to Convert JSON to Hash in Ruby?
In this article, we will discuss how to convert JSON to hash in Ruby. We can convert JSON to hash through different methods ranging from parsing JSON and JSON.load to using YAML.safe_load Method. Table of Content Using JSON.parse MethodUsing JSON.load MethodUsing YAML.safe_load Method Using JSON.par
2 min read
How to Parse Hash in Ruby?
Parsing a hash in Ruby entails gaining access to its keys and values, iterating over them, and carrying out any necessary actions. The article focuses on discussing the ways to parse a hash in Ruby. Table of Content Iterating through a HashAccessing Hash ElementsSorting a HashIterating through a Has
2 min read
How to Check if an Array Contains a Value in Ruby?
In this article, we will discuss how to check if an array contains a specific value in ruby. We can check if an array contains a specific value through different methods ranging from using include? method and member? method to any? method Table of Content Check if an Array Contains a Value using inc
3 min read
How to find a hash key containing a matching value?
In this article, we will discuss how to find a hash key containing a matching value in ruby. We can find a hash key containing a matching value through different methods ranging from using Hash#key method and Hash#select method to any? method Table of Content Finding a hash key containing a matching
3 min read
How to check if a value exists in an Array in Ruby?
In this article, we will discuss how to check if a value exists in an array in ruby. We can check if a value exists in an array through different methods ranging from using Array#member? method and Array#include? method to Array#any? method Table of Content Check if a value exists in an array using
3 min read
How to Make a Custom Array of Hashes in Ruby?
Prerequisites: Hashes and Arrays in Ruby Arrays and hashes are data structures that allow you to store multiple values at once. In this article, we will explore their syntax, how to combine functionalities of both to create an array of hashes, retrieve values, and loop through them. An array is a co
3 min read