Array of hashes to hash
You can use .inject
:
a.inject(:merge)#=> {:a=>:b, :c=>:d}
Which initiates a new hash on each iteration from the two merged. To avoid this, you can use destructive :merge!
( or :update
, which is the same):
a.inject(:merge!)#=> {:a=>:b, :c=>:d}
These two:
total_hash = hs.reduce({}) { |acc_hash, hash| acc_hash.merge(hash) }total_hash = hs.reduce({}, :merge)
Note that Hash#merge
creates a new hash on each iteration, which may be a problem if you are building a big hash. In that case, use update
instead:
total_hash = hs.reduce({}, :update)
An alternative approach would be to convert the hashes to pairs and then build the final hash:
total_hash = hs.flat_map(&:to_a).to_h