Array of hashes to hash

后端 未结 7 611
遥遥无期
遥遥无期 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:11

    I came across this answer and I wanted to compare the two options in terms of performance to see which one is better:

    1. a.reduce Hash.new, :merge
    2. a.inject(:merge)

    using the ruby benchmark module, it turns out that option (2) a.inject(:merge) is faster.

    code used for comparison:

    require 'benchmark'
    
    input = [{b: "c"}, {e: "f"}, {h: "i"}, {k: "l"}]
    n = 50_000
    
    Benchmark.bm do |benchmark|
      benchmark.report("reduce") do
        n.times do
          input.reduce Hash.new, :merge
        end
      end
    
      benchmark.report("inject") do
        n.times do
          input.inject(:merge)
        end
      end
    end
    

    the results were

           user     system      total        real
    reduce  0.125098   0.003690   0.128788 (  0.129617)
    inject  0.078262   0.001439   0.079701 (  0.080383)
    

提交回复
热议问题