Array of hashes to hash

后端 未结 7 606
遥遥无期
遥遥无期 2020-12-12 15:20

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}
         


        
相关标签:
7条回答
  • 2020-12-12 16:24

    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
    
    0 讨论(0)
提交回复
热议问题