拥有这个散列数组:
a = [{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}]
我想得到一个完整的扁平散列如下:
{"red"=>"130", "blue"=>"94", "green"=>"57"}
最佳答案
使用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)
# => {}