Home »
Ruby programming
Hashes in Ruby
Ruby Hashes: In this tutorial, we are going to learn about the Hash collection in Ruby programming language with example.
Submitted by Hrithik Chandra Prasad, on October 03, 2019
Ruby Hash Collection
In Ruby, hashes are the collection of identical keys and their values. They are like dictionaries, which has an element along with its description. You can retrieve any available value with the help of a key associated with it. It is alike arrays, but here, you can use indexes of an object type, instead of only integer types. Hashes can also be termed as dictionaries, maps, and associative arrays.
You will get nil as return statement if you try to access a hash with a key and that key does not exist.
Now, let us see how we create a hash in Ruby?
You can create a hash inside {} (curly braces). => symbol is required to provide values to the key and to provide multiple key/values to the hash, a comma is used.
Syntax:
hash_name = {"key1"=> "value", "key2"=> "value", "key3"=> "value"}
#or
hash_name["key"] = "value"
#or
hash_name = {key1: "value1", key2: "value2", key3: "value3"}
Now, let us understand the concept with the help of some examples given below,
Example 1:
id = {
"AA101" => "Suresh",
"AA102" => "Sanjiv",
"AA103" => "Dam",
"AA104" => "Swati",
"AA105" => "Kamlesh"
}
id.each do |key, value|
puts "#{key} = #{value}"
end
Output
AA101 = Suresh
AA102 = Sanjiv
AA103 = Dam
AA104 = Swati
AA105 = Kamlesh
Explanation:
In the above code, we have created a hash with our values by putting it inside curly braces. We are then printing the hash with the help of each method. The hash is having the record of students along with their id. This is the advantage of hashes that we don't have only integer indexes.
Example 2:
fruit = {"banana"=>"yellow"}
puts "Enter the number of key/value you want to enter"
i = gets.chomp.to_i
while (i!=0)
puts "Enter key:"
x = gets.chomp
puts "Enter value:"
v = gets.chomp
fruit.store(x,v)
i=i-1
end
fruit.each do |key, value|
puts "#{key}'s color is #{value}"
end
Output
Enter the number of key/value you want to enter
4
Enter key:
Apple
Enter value:
Red
Enter key:
Grapes
Enter value:
Green
Enter key:
Mango
Enter value:
Yellow
Enter key:
Kiwiw
Enter value:
Green
banana's color is yellow
Apple's color is Red
Grapes's color is Green
Mango's color is Yellow
Kiwiw's color is Green
Explanation:
In the above program, we are trying to create a hash with the help of user input values. We have first declared a hash with our values. Then we have asked the user for the number of values she wants to store in the hash. We are making use of the hash.store method to store the user input keys and their corresponding values. At last, we are printing all the values with the help of .each method.
Hash Methods