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:
Ruby
# Ruby program to illustrate how to access
# the element of the array of hashes
# Creating an array of hashes
hash_arr = [ {"name" => 'GeeksforGeeks', "branch" => 'CSE'},
{:language1 => 'Ruby', :language2 => 'Python'} ]
# Accessing the elements of hash_arr
res1 = hash_arr[0]["branch"]
res2 = hash_arr[1][:language1]
# Display the results
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:
ruby
# Ruby program to illustrate how to access
# the element of the array of hashes
# Creating an array of hashes
hash_arr = [ {name: 'Amu', occupation: 'Web developer', hobbies: 'Painting'},
{name: 'Sumit', occupation: 'HR', hobbies: 'Swimming'} ]
# Iterate over the array of hashes
# Using .each do statement
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 # Ruby p
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 convert a number to Binary in Ruby?
In Ruby, converting a number to binary involves utilizing built-in methods or implementing custom algorithms. Binary representation is a base-2 numeral system, where each digit can be either 0 or 1. There are many ways to convert a number to binary in Ruby like: Using String Interpolation with %b Fo
2 min read
How to Create a Linked List in Ruby?
A linked list is a form of linear data structure whereby the elements are not positioned closely together in memory. Each element here instead points to the subsequent one, thus leading to a chain-like arrangement. Creating a linked list in Ruby entails defining an information structure where each n
5 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 ContentPrerequisites What is Hash?Creating Hashes Accessing Hash ValuesAddin
5 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 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