Open In App

How to Make a Custom Array of Hashes in Ruby?

Improve
Improve
Like Article
Like
Save
Share
Report

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 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 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 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.



Last Updated : 03 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads