Merge arrays to hash and use duplicates [closed]

强颜欢笑 提交于 2019-12-25 03:56:06

问题


How do I keep duplicates and maintain order? For example:

keys   = [1, 2, 1]
values = ["a", "b", "c"]
Hash[keys.zip(values)] # => {1=>"c", 2=>"b"}

回答1:


As Justin & Luca said:

Hashes don't allow duplicate keys.

Best you can do is by having array of values, found this solution in this SO question:

Hash.new.tap { |h| keys.zip(values).each { |k, v| (h[k] ||= []) << v } }
# => {1=>["a", "c"], 2=>["b"]} 



回答2:


You cannot keep duplicates if you use the keys array as hash key. They must be unique



来源:https://stackoverflow.com/questions/25446731/merge-arrays-to-hash-and-use-duplicates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!