合并两个哈希数组

时间:2013-12-12 06:39:22

标签: ruby merge

我正在尝试通过哈希中的键合并两个哈希数组。例如,如果我有:

local = [{:name => 'foo', :values => [2, 7], :desc => 'my foo'}, {:name => 'bar', :values => [3, 8], :desc => 'my bar'}]
remote = [{:name => 'baz', :values => [4, 1], :desc => 'this baz'}, {:name => 'foo', :values => [5, 7], :desc => 'this foo'}]

我希望合并为:

[{:name => 'foo', :values => [2, 5, 7], :desc => 'my foo'}, {:name => 'bar', :values => [3,8], :desc => 'my bar'}, {:name => 'baz', :values => [4,1], :desc => 'this baz'}]

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

作为一种变体(我认为你有一个线索):

local = [{:name => 'foo', :values => [2, 7], :desc => 'my foo'}, {:name => 'bar', :values => [3, 8], :desc => 'my bar'}]
remote = [{:name => 'baz', :values => [4, 1], :desc => 'this baz'}, {:name => 'foo', :values => [5, 7], :desc => 'this foo'}]

p (local + remote)
  .group_by{|el| el[:name]}
  .map{|_,el| el.inject{|h, e| h[:values] |= e[:values]; h}}
# => [{:name=>"foo", :values=>[2, 7, 5], :desc=>"my foo"}, {:name=>"bar", :values=>[3, 8], :desc=>"my bar"}, {:name=>"baz", :values=>[4, 1], :desc=>"this baz"}]

答案 1 :(得分:0)

让我们说这段代码可以做到。

def deep_merge a1, a2
   r = []
   a1.each do| v1 |
      p v1
      v = v1.dup
      a2.map! do| v2 |
         if v2[ :name ] == v[ :name ]
            v[ :values ] |= v2[ :values ]
            nil
         else
            v2
         end
      end.compact!
      r << v
   end
   a2.compact.map do| v2 |
      r << v2
   end
   r
end

local = [{:name => 'foo', :values => [2, 7], :desc => 'my foo'}, {:name => 'bar', :values => [3, 8], :desc => 'my bar'}]
remote = [{:name => 'baz', :values => [4, 1], :desc => 'this baz'}, {:name => 'foo', :values => [5, 7], :desc => 'this foo'}]

pp = deep_merge local, remote

# => [{:name=>"foo", :values=>[2, 7, 5], :desc=>"my foo"}, {:name=>"bar", :values=>[3, 8], :desc=>"my bar"}, {:name=>"baz", :values=>[4, 1], :desc=>"this baz"}]