4

I want to merge array of hashes by prioritizing non-nil values.

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 better way to implement this function?

ironsand
  • 14,329
  • 17
  • 83
  • 176

1 Answers1

0

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 { |_, v| !v }
  .flatten(1)
  .to_h
# => { :c => 3, :a => 1, :b => 2, :d => nil, :e => 5 }
spren9er
  • 744
  • 8
  • 11