How to Make a Custom Array of Hashes in Ruby?
Last Updated :
03 Jul, 2020
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 collection of different or similar items, stored at contiguous memory locations. The idea is to store multiple items of the same type together, which can be referred to by a common name.
Here is how an array is declared in Ruby:
arr = ["Geeks", 55, 61, "GFG"]
Hash is a data structure that maintains a set of objects which are termed as the keys and each key associates a value with it. In simple words, a hash is a collection of unique keys and their values.
Here is how an array is declared in Ruby:
hash_variable = {
"key1" => "Geeks",
"key2" => "for",
"key2" => "Geeks"
}
Creating an array of hashes
You are allowed to create an array of hashes either by simply initializing array with hashes or by using array.push() to push hashes inside the array.
A simple method to create an array of hashes:
hash_arr = [ {"height" => '5 ft', "weight" => '170 lbs',
"hair" => 'white'},
{:pet => 'Cat', :nest => 'Bird'} ]
Or Using array.push() to push hashes inside the array:
hash_arr = []
hash1 = {"height" => '5 ft', "weight" => '170 lbs', "hair" => 'White'}
hash2 = {:pet => 'Frog', :nest => 'Bird'}
hash_arr.push(hash1)
hash_arr.push(hash2)
Note: Both “Key” and :Key acts as a key in a hash in ruby.
Accessing an array of hashes
You can access the elements of an array of hashes by using array-based indexing to access a particular hash and keys to access values present in that hash.
hash_arr = [ {"height" => '5 ft', "weight" => '170 lbs',
"hair" => 'white'},
{:pet => 'Cat', :nest => 'Bird'} ]
hash_arr[0]["height"] #=> '5 ft'
hash_arr[1][:nest] #=> 'Bird'
Example:
hash_arr = [ { "name" => 'GeeksforGeeks' , "branch" => 'CSE' },
{ :language1 => 'Ruby' , :language2 => 'Python' } ]
res1 = hash_arr[ 0 ][ "branch" ]
res2 = hash_arr[ 1 ][ :language1 ]
puts res1
puts res2
|
Output:
CSE
Ruby
Iterate over the array of hashes
You can use simple .each do statements to iterate over the array of hashes:
Example:
hash_arr = [ {name: 'Amu' , occupation: 'Web developer' , hobbies: 'Painting' },
{name: 'Sumit' , occupation: 'HR' , hobbies: 'Swimming' } ]
hash_arr. each do |hash|
puts 'Values in this Hash'
hash. each do |key,value|
puts (key.to_s + ': ' + value.to_s)
end
end
|
Output:
Values in this Hash
name: Amu
occupation: Web developer
hobbies: Painting
Values in this Hash
name: Sumit
occupation: HR
hobbies: Swimming
Note: .to_s is used to convert all values into strings so they can be easily printed.
Similar Reads
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 Access elements of nested hashes in Ruby?
RIn this article, we will discuss how to access elements of nested hashes in Ruby. We can access elements of nested hashes through different methods ranging from using the dig method to the fetch method. Table of Content Access elements of nested hashes using square bracketsAccess elements of nested
2 min read
How to iterate over a Hash in Ruby?
In this article, we will discuss how to iterate over a hash in Ruby. By Iterating over a hash we can access key-value pairs and perform operations on them. Let us study different methods to iterate over a hash in ruby Table of Content Iterating over a hash using each methodIterating over a hash usin
2 min read
How to access array Elements in Ruby
In this article, we will learn how to access array elements in Ruby. In Ruby, there are several ways to retrieve the elements from the array. Ruby arrays provide a lot of different methods to access the array element. But the most used way is to use the index of an array. Using Index - # Ruby progra
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 can we access the entries of a Hash in Ruby?
In this article, we will discuss how to access the entries of a Hash in ruby. We can access the entries of a Hash through different methods ranging from using keys, and values to each method Table of Content Accessing the entries of a Hash using Hash.keys methodAccessing the entries of a Hash using
2 min read
How to Add Key and Value to Hash in Ruby?
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. Table of Content Prerequisites What is Hash?Creating Hashes Accessing Hash ValuesAdd
6 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 initialize array in Ruby
In this article, we will learn how to initialize the array in Ruby. There are several ways to create an array. Let's see each of them one by one. Using the new class method: new method can be used to create the arrays with the help of dot operator. Using arguments we can provide the size to array an
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