How to build a Ruby hash out of two equally-sized arrays?

前端 未结 4 1472
花落未央
花落未央 2020-12-22 20:40

I have two arrays

a = [:foo, :bar, :baz, :bof]

and

b = [\"hello\", \"world\", 1, 2]

I want



        
4条回答
  •  隐瞒了意图╮
    2020-12-22 21:11

    Just for curiosity's sake:

    require 'fruity'
    
    a = [:foo, :bar, :baz, :bof]
    b = ["hello", "world", 1, 2]
    
    compare do
      jtbandes { h = Hash[a.zip b] }
      lethjakman { h = a.zip(b).to_h }
      junichi_ito1 { [a, b].transpose.to_h }
      junichi_ito2 { Hash[ [a, b].transpose ] } 
    end
    
    # >> Running each test 8192 times. Test will take about 1 second.
    # >> lethjakman is similar to junichi_ito1
    # >> junichi_ito1 is similar to jtbandes
    # >> jtbandes is similar to junichi_ito2
    
    compare do 
      junichi_ito1 { [a, b].transpose.to_h }
      junichi_ito2 { Hash[ [a, b].transpose ] } 
    end
    
    # >> Running each test 8192 times. Test will take about 1 second.
    # >> junichi_ito1 is faster than junichi_ito2 by 19.999999999999996% ± 10.0%
    

提交回复
热议问题