Rails mapping array of hashes onto single hash

后端 未结 4 1079
情书的邮戳
情书的邮戳 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"}
    
    0 讨论(0)
  • 2021-01-30 12:51

    How about:

    h = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
    r = h.inject(:merge)
    
    0 讨论(0)
  • 2021-01-30 13:01

    You could compose Enumerable#reduce and Hash#merge to accomplish what you want.

    input = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
    input.reduce({}, :merge)
      is {"testPARAM2"=>"testVAL2", "testPARAM1"=>"testVAL1"}
    

    Reducing an array sort of like sticking a method call between each element of it.

    For example [1, 2, 3].reduce(0, :+) is like saying 0 + 1 + 2 + 3 and gives 6.

    In our case we do something similar, but with the merge function, which merges two hashes.

    [{:a => 1}, {:b => 2}, {:c => 3}].reduce({}, :merge)
      is {}.merge({:a => 1}.merge({:b => 2}.merge({:c => 3})))
      is {:a => 1, :b => 2, :c => 3}
    
    0 讨论(0)
  • 2021-01-30 13:05

    Use #inject

    hashes = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
    merged = hashes.inject({}) { |aggregate, hash| aggregate.merge hash }
    merged # => {"testPARAM1"=>"testVAL1", "testPARAM2"=>"testVAL2"}
    
    0 讨论(0)
提交回复
热议问题