How to combine an array of hashes by prioritizing non-nil values

I want to combine an array of hashes with non-nil priorities.

I wrote like this:

hs = [{a: 1, b:2, c: nil},{a: nil, b:nil, c:3},{d: nil, e: 5}]
hs.reduce{|v1,v2| v1.merge(v2){|k,old,new| old || new} }
# => {:a=>1, :b=>2, :c=>3, :d=>nil, :e=>5}

Is there a better way to implement this feature?

+4
source share
1 answer

No, probably not. An alternative would be

hs = [{a:1, b:2, c:nil}, {a:nil, b:nil, c:3}, {d:nil, e:5}]
hs.map(&:to_a).flatten(1).partition{|p| !p[1]}.map(&:to_h).inject(&:merge)
# => {:c=>3, :a=>1, :b=>2, :d=>nil, :e=>5}
0
source

Source: https://habr.com/ru/post/1605710/


All Articles