合并阵列中的每个第3个哈希

时间:2014-02-17 17:29:36

标签: ruby arrays merge hash

您好我找不到如何合并数组的每3个哈希值。 这是我的哈希数组。

     [
      {:key1=>"v1"}, {:ky2 => "v2"}, {:key3 => "v3"}, 
      {:key1=>"v4"}, {:ky2 => "v5"}, {:key3 => "v6"},
      {:key1=>"v7"}, {:ky2 => "v8"}, {:key3 => "v9"},..
     ]

我需要的是将每3个哈希合并为:

      [
       {:key1=>"v1", :ky2 => "v2", :key3 => "v3"}, 
       {:key1=>"v4", :ky2 => "v5", :key3 => "v6"},
       {:key1=>"v7", :ky2 => "v8", :key3 => "v9"},..
      ]

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

我会做

hs = [
      {:key1=>"v1"}, {:ky2 => "v2"}, {:key3 => "v3"}, 
      {:key1=>"v4"}, {:ky2 => "v5"}, {:key3 => "v6"},
      {:key1=>"v7"}, {:ky2 => "v8"}, {:key3 => "v9"}
     ]

hs.each_slice(3).map { |grouped_hs| grouped_hs.inject(:merge) }
# => [{:key1=>"v1", :ky2=>"v2", :key3=>"v3"},
#     {:key1=>"v4", :ky2=>"v5", :key3=>"v6"},
#     {:key1=>"v7", :ky2=>"v8", :key3=>"v9"}]

答案 1 :(得分:1)

a.flat_map(&:to_a).each_slice(3).map(&:to_h)
  #=> [{:key1=>"v1", :ky2=>"v2", :key3=>"v3"},
  #=>  {:key1=>"v4", :ky2=>"v5", :key3=>"v6"},
  #=>  {:key1=>"v7", :ky2=>"v8", :key3=>"v9"}]
在v2.1中添加了

Array#to_h

答案 2 :(得分:0)

a = [
  { :key1=>'v1' }, { :ky2 => 'v2' }, { :key3 => 'v3' }, 
  { :key1=>'v4' }, { :ky2 => 'v5' }, { :key3 => 'v6' },
  { :key1=>'v7' }, { :ky2 => 'v8' }, { :key3 => 'v9' }
]

a.each_slice(3).map{ |e| e.inject(&:merge) }