我是Ruby的新手,不知道如何将新项添加到已经存在的哈希.例如,首先我构造哈希:
hash = {item1: 1}
Run Code Online (Sandbox Code Playgroud)
之后想要添加item2所以在此之后我有这样的哈希:
{item1: 1, item2: 2}
Run Code Online (Sandbox Code Playgroud)
我不知道哈希上有什么方法可以帮助我吗?
pju*_*ble 281
创建哈希:
hash = {:item1 => 1}
Run Code Online (Sandbox Code Playgroud)
添加一个新项目:
hash[:item2] = 2
Run Code Online (Sandbox Code Playgroud)
Ale*_*der 67
如果要从另一个哈希添加新项目 - 使用merge方法:
hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}
Run Code Online (Sandbox Code Playgroud)
在您的具体情况下,它可能是:
hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}
Run Code Online (Sandbox Code Playgroud)
但是当你应该多添加一个元素时,使用它是不明智的.
注意merge将使用现有密钥替换值:
hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}
Run Code Online (Sandbox Code Playgroud)
完全一样 hash[:item1] = 2
此外,您应该注意merge方法(当然)不会影响哈希变量的原始值 - 它返回一个新的合并哈希.如果要替换哈希变量的值,请merge!改为使用:
hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}
Run Code Online (Sandbox Code Playgroud)
shi*_*ovk 28
hash.store(key,value) - 在哈希中存储键值对.
例:
hash #=> {"a"=>9, "b"=>200, "c"=>4}
hash.store("d", 42) #=> 42
hash #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
Run Code Online (Sandbox Code Playgroud)
Nik*_* B. 25
它很简单:
irb(main):001:0> hash = {:item1 => 1}
=> {:item1=>1}
irb(main):002:0> hash[:item2] = 2
=> 2
irb(main):003:0> hash
=> {:item1=>1, :item2=>2}
Run Code Online (Sandbox Code Playgroud)
Con*_*ech 14
hash [key] = value将value给出的值与key给出的键相关联.
hash[:newKey] = "newValue"
Run Code Online (Sandbox Code Playgroud)
从Ruby文档:http: //www.tutorialspoint.com/ruby/ruby_hashes.htm
hash_items = {:item => 1}
puts hash_items
#hash_items will give you {:item => 1}
hash_items.merge!({:item => 2})
puts hash_items
#hash_items will give you {:item => 1, :item => 2}
hash_items.merge({:item => 2})
puts hash_items
#hash_items will give you {:item => 1, :item => 2}, but the original variable will be the same old one.
Run Code Online (Sandbox Code Playgroud)