问题
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