For example, I have array of single hashes
a = [{a: :b}, {c: :d}]
What is best way to convert it into this?
{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