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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

CSE
Ruby

Iterate over the array of hashes

You can use simple .each do statements to iterate over the array of hashes:
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.