Ruby散列有点扁平化

时间:2014-12-09 10:10:34

标签: ruby hash

拥有这个哈希数组,:

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

我希望像这样得到一个完整的扁平哈希:

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

4 个答案:

答案 0 :(得分:3)

[{"red"=>"130"}, {"blue"=>"94"}, {"green"=>"57"}].reduce(:merge)
# => {"red"=>"130", "blue"=>"94", "green"=>"57"} 

注意:

  1. 将为空数组返回nil
  2. 两者:Enumerable#reduceEnumerable#inject都可以使用

答案 1 :(得分:2)

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

答案 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]
# => {}