ruby 如何将多个值添加到同一个键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19728965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add several values to the same key
提问by user2211703
how can I add several values to the same key? Something like this:
如何将多个值添加到同一个键?像这样的东西:
x = {}
x["k1"] = nil
x["k1"] << {"a" => "a"}
x["k1"] << {"b" => "b"}
well, this doesn't work like with array.
好吧,这与数组不同。
回答by Arup Rakshit
You can do as below :
您可以执行以下操作:
For Arrayas value to the key of a Hash:
对于Array作为价值的关键Hash:
h = Hash.new{|hsh,key| hsh[key] = [] }
h['k1'].push 'a'
h['k1'].push 'b'
p h # >> {"k1"=>["a", "b"]}
For Hashas value to the key of a Hash:
对于Hash作为价值的关键Hash:
h = Hash.new{|hsh,key| hsh[key] = {} }
h['k1'].store 'a',1
h['k1'].store 'b',1
p h # >> {"k1"=>{"a"=>1, "b"=>1}}
回答by Some Guy
Depends on just what you're trying to accomplish here. If you want a hash of arrays, that's easy enough:
取决于你想在这里完成什么。如果你想要一个数组的散列,那很容易:
x = {}
x['k1'] = Array.new
x['k1'] << 'a'
x['k1'] << 'b'
or if you want nested hashes, simple enough as well
或者如果你想要嵌套的哈希,也很简单
x = {}
x['k1'] = {}
x['k1']['a'] = 'a'
x['k1']['b'] = 'b'
the values in a hash are just objects. They can be arrays, other hashes, or whatever else you might want.
散列中的值只是对象。它们可以是数组、其他散列或您可能想要的任何其他内容。
回答by struthersneil
So, you want the value of key 'k1' to be a hash, and you want to add key/value pairs to that hash. You can do it like this:
因此,您希望键 'k1' 的值是一个散列,并且您希望将键/值对添加到该散列中。你可以这样做:
2.0.0-p195 :111 > x = {}
=> {}
2.0.0-p195 :112 > x['k1'] = { 'a' => '1' }
=> {"a"=>"1"}
2.0.0-p195 :117 > x['k1'].merge!({ 'b' => '2' })
=> {"a"=>"1", "b"=>"2"}
Or, you can do it like this:
或者,您可以这样做:
2.0.0-p195 :119 > x['k1']['c'] = 3
=> 3
2.0.0-p195 :120 > x['k1']
=> {"a"=>"1", "b"=>"2", "c"=>3}
回答by toms
The short answer is you can't: a hash key has only one value by definition.
In addition, you are trying to use the shovel operator <<, an array method, to set the value. But even if you used =, every time you set the key to a new value, the old value is lost:
简短的回答是你不能:根据定义,哈希键只有一个值。此外,您正在尝试使用 shovel 运算符<<(一种数组方法)来设置值。但即使你使用了=,每次你将键设置为新值时,旧值也会丢失:
x = {}
=> {}
x["k1"] = {"a" => "a"}
=> {"a"=>"a"}
x["k1"] = {"b" => "b"}
=> {"b"=>"b"}
As others have pointed out, if you want "several values" per key, you should use some kind of collection
正如其他人指出的那样,如果您希望每个键有“几个值”,则应该使用某种集合
x = {}
=> {}
x["k1"] = {"a" => "a", "b" => "b"}
=> {"a"=>"a", "b"=>"b"}

