我有以下数组:
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
我想将它转换为1个大哈希但保留所有值,所以我希望它看起来如下:
{"a" => [2, nil], "b" => [3, nil], "c" => [2]}
我可以接近array.inject({}) {|s, h| s.merge(h)}}
,但它会覆盖这些值。
答案 0 :(得分:2)
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
a = array.each_with_object(Hash.new([])) do |h1,h|
h1.each{|k,v| h[k] = h[k] + [v]}
end
a # => {"a"=>[2, nil], "b"=>[3, nil], "c"=>[2]}
答案 1 :(得分:0)
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
res = {}
array.each do |hash|
hash.each do |k, v|
res[k] ||= []
res[k] << v
end
end