Array of hashes to hash

后端 未结 7 608
遥遥无期
遥遥无期 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条回答
  •  -上瘾入骨i
    2020-12-12 16:14

    You can transform it to array [[:a, :b]] and after that translate everything to hash {:a=>:b}

    # it works like [[:a, :b]].to_h => {:a=>:b}
    
    [{a: :b}, {c: :d}].map { |hash| hash.to_a.flatten }.to_h
    
    # => {:a=>:b, :c=>:d}
    

提交回复
热议问题