Creating a hash from two arrays with identical val

2019-09-07 21:39发布

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

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

works perfectly it gives me exactly what I need => {"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"}

Any help is appreciated

标签: ruby arrays hash
1条回答
等我变得足够好
2楼-- · 2019-09-07 22:15

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?

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"]}
查看更多
登录 后发表回答