您好我找不到如何合并数组的每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"},..
]
提前感谢您的帮助。
答案 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中添加了
答案 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) }