拥有这个散列数组:

a = [{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}]

我想得到一个完整的扁平散列如下:
{"red"=>"130", "blue"=>"94", "green"=>"57"}

最佳答案

使用Enumerable#injectHash#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)
# => {}

10-07 18:22