拥有这个哈希数组,:
a = [{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}]
我希望像这样得到一个完整的扁平哈希:
{"red"=>"130", "blue"=>"94", "green"=>"57"}
答案 0 :(得分:3)
[{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}].reduce(:merge)
# => {"red"=>"130", "blue"=>"94", "green"=>"57"}
nil
答案 1 :(得分:2)
使用Enumerable#inject
和Hash#merge
:
a = [{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}]
a.inject(:merge)
# => {"red"=>"130", "blue"=>"94", "green"=>"57"}
注意如果数组为空,则返回nil
。
a = []
a.inject(:merge) # <---
# => nil
a.inject({}, :merge)
# => {}
答案 2 :(得分:1)
使用each_with_object(obj)
的另一种方式:
a = [{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}]
a.each_with_object({}) { |h, o| o[h.keys.first] = h.values.first }
{"red"=>"130", "blue"=>"94", "green"=>"57"}
如果数组为空,则返回空哈希{}
。
答案 3 :(得分:1)
Hash[*a.map(&:to_a).flatten]
# => {"red"=>"130", "blue"=>"94", "green"=>"57"}
为空数组返回空哈希
Hash[*[].map(&:to_a).flatten]
# => {}