ruby - How do I merge two hashes into a hash of arrays? -
i'd merge these 2 arrays:
a = { :a => 'a', :b => 'b', :d => 'd' } b = { :a => '1', :b => 'b', :c => 'c' }
into hash looks this:
{:a => ["a", "1"], :b => ["b", "b"], :c => [nil, "c"], :d => ["d", nil] }
this doesn't work:
p a.merge(b) { |k, v1, v2| [v1, v2] } # {:c=>"c", :a=>["a", "1"], :b=>["b", "b"], :d=>"d"}
it's because hash#merge
call block duplicate keys.
a = { :a => 'a', :b => 'b', :d => 'd' } b = { :a => '1', :b => 'b', :c => 'c' } hash[(a.keys|b.keys).map { |key| [key, [a.fetch(key, nil), b.fetch(key, nil)]] }] # => {:a=>["a", "1"], :b=>["b", "b"], :d=>["d", nil], :c=>[nil, "c"]} # in ruby 2.1+ (a.keys|b.keys).map { |key| [key, [a.fetch(key, nil), b.fetch(key, nil)]] }.to_h
Comments
Post a Comment