Rails mapping array of hashes onto single hash

后端 未结 4 1118
情书的邮戳
情书的邮戳 2021-01-30 12:08

I have an array of hashes like so:

 [{\"testPARAM1\"=>\"testVAL1\"}, {\"testPARAM2\"=>\"testVAL2\"}]

And I\'m trying to map this onto sin

4条回答
  •  青春惊慌失措
    2021-01-30 12:49

    Here you can use either inject or reduce from Enumerable class as both of them are aliases of each other so there is no performance benefit to either.

     sample = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
    
     result1 = sample.reduce(:merge)
     # {"testPARAM1"=>"testVAL1", "testPARAM2"=>"testVAL2"}
    
     result2 = sample.inject(:merge)
     # {"testPARAM1"=>"testVAL1", "testPARAM2"=>"testVAL2"}
    

提交回复
热议问题