Home »
Ruby Tutorial
Ruby Hash.store(key, value) Method
By IncludeHelp Last updated : December 01, 2024
In this article, we will study about Hash.store(key, value) Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.
Description and Usage
This method is a public instance method that is defined in the ruby library especially for Hash class. This method works in a way that it stores or assigns the given value into the key with which the method has been invoked. This method takes two parameters, one is
the key and another one is the value of that particular key.
This method does bring change in the actual hash because this method belongs to the category of destructive methods.
Syntax
Hash_object.store(key,value)
Parameters
This method takes two parameters, one is the key and another one is the value of that particular key.
Example 1
=begin
Ruby program to demonstrate store method
=end
hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash store implementation"
puts "Enter the key:"
ky = gets.chomp
puts "Enter the value:"
val = gets.chomp
hsh = hash1.store(ky,val)
puts "Key updated is #{hsh}"
puts "Self hash object : #{hash1}"
Output
Hash store implementation
Enter the key:
color
Enter the value:
blue
Key updated is blue
Self hash object : {"color"=>"blue", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}
Explanation
In the above code, you can observe that we are storing values in the hash object with the help of the Hash.store() method. You can see how we can update the value of a particular key in the hash object with the help of this method? This method is creating changes in the actual hash object because this method is one of the examples of destructive methods.
Example 2
=begin
Ruby program to demonstrate store method
=end
hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash store implementation"
hsh = hash1.store("City","Jaipur")
puts "Value updated is #{hsh}"
puts "Self hash object : #{hash1}"
Output
Hash store implementation
Value updated is Jaipur
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato", "City"=>"Jaipur"}
Explanation
In the above code, you can observe that we are storing values in the hash object with the help of the Hash.store() method. You can see that even if the key does not exist, this method will add a new key along with its value at the last index of the hash instance. This method is creating changes in the actual hash object because this method is one of the examples of destructive methods.