Ruby中带有示例的Hash.store(key,value)方法
Hash.store(key,value)方法
在本文中,我们将研究Hash.store(key,value)方法。可以借助其名称来预测此方法的工作,但是它并不像看起来那样简单。好吧,我们将在其余内容中借助其语法和程序代码来理解此方法。
方法说明:
此方法是在ruby库中定义的公共实例方法,特别是针对Hash类。此方法的工作方式是将给定值存储或分配给调用该方法的键。此方法有两个参数,一个是
键,另一个是该特定键的值。
由于此方法属于破坏性方法的类别,因此它的确会带来实际哈希值的变化。
语法:
Hash_object.store(key,value)
Argument(s)需要:
此方法采用两个参数,一个是键,另一个是该特定键的值。
范例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}"输出结果
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"}说明:
在上面的代码中,您可以观察到我们借助于哈希将值存储在哈希对象中。store()方法。您可以看到如何借助此方法更新哈希对象中特定键的值?因为此方法是破坏性方法的示例之一,所以该方法正在实际的哈希对象中创建更改。
范例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}"输出结果
Hash store implementation
Value updated is Jaipur
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato", "City"=>"Jaipur"}说明:
在上面的代码中,您可以观察到我们借助于哈希将值存储在哈希对象中。store()方法。您可以看到,即使键不存在,此方法也会在哈希实例的最后一个索引处添加一个新键及其值。因为此方法是破坏性方法的示例之一,所以该方法正在实际的哈希对象中创建更改。