在Ruby中使用具有相同值的两个数组创建哈希

时间:2021-06-06 12:54:18

I'm having issues creating a hash from 2 arrays when values are identical in one of the arrays. e.g.

当其中一个数组中的值相同时,我遇到了从2个数组创建哈希的问题。例如

names = ["test1", "test2"]
numbers = ["1", "2"]
Hash[names.zip(numbers)]

works perfectly it gives me exactly what I need => {"test1"=>"1", "test2"=>"2"}

完美的工作它给了我我所需要的东西=> {“test1”=>“1”,“test2”=>“2”}

However if the values in "names" are identical then it doesn't work correctly

但是,如果“名称”中的值相同,则它无法正常工作

names = ["test1", "test1"]
numbers = ["1", "2"]
Hash[names.zip(numbers)] 

shows {"test1"=>"2"} however I expect the result to be {"test1"=>"1", "test1"=>"2"}

显示{“test1”=>“2”}但是我希望结果为{“test1”=>“1”,“test1”=>“2”}

Any help is appreciated

任何帮助表示赞赏

1 个解决方案

#1


3  

Hashes can't have duplicate keys. Ever.

哈希不能有重复的键。永远。

If they were permitted, how would you access "2"? If you write myhash["test1"], which value would you expect?

如果他们被允许,您将如何访问“2”?如果你写myhash [“test1”],你会期望哪个值?

Rather, if you expect to have several values under one key, make a hash of arrays.

相反,如果您希望在一个键下有多个值,请创建一个数组哈希。

names = ["test1", "test1", "test2"]
numbers = ["1", "2", "3"]

Hash.new.tap { |h| names.zip(numbers).each { |k, v| (h[k] ||= []) << v } }
# => {"test1"=>["1", "2"], "test2"=>["3"]}

#1


3  

Hashes can't have duplicate keys. Ever.

哈希不能有重复的键。永远。

If they were permitted, how would you access "2"? If you write myhash["test1"], which value would you expect?

如果他们被允许,您将如何访问“2”?如果你写myhash [“test1”],你会期望哪个值?

Rather, if you expect to have several values under one key, make a hash of arrays.

相反,如果您希望在一个键下有多个值,请创建一个数组哈希。

names = ["test1", "test1", "test2"]
numbers = ["1", "2", "3"]

Hash.new.tap { |h| names.zip(numbers).each { |k, v| (h[k] ||= []) << v } }
# => {"test1"=>["1", "2"], "test2"=>["3"]}