将Ruby哈希数组转换为一个哈希值

时间:2022-06-03 09:58:29

I have the following array:

我有以下数组:

array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]

I want to convert it into 1 big hash but keep all of the values, so I want it to look like the following:

我想将它转换为1个大哈希但保留所有值,所以我希望它看起来如下所示:

{"a" => [2, nil], "b" => [3, nil], "c" => [2]}

I can get close doing array.inject({}) {|s, h| s.merge(h)}}, but it overwrites the values.

我可以接近做array.inject({}){| s,h | s.merge(h)}},但它会覆盖这些值。

2 个解决方案

#1


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]}

#2


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

#1


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]}

#2


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