What is the best way to convert an array to a hash in Ruby

后端 未结 11 2018
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 18:18

In Ruby, given an array in one of the following forms...

[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]

...what is the best way to convert

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 18:53

    You can also simply convert a 2D array into hash using:

    1.9.3p362 :005 > a= [[1,2],[3,4]]
    
     => [[1, 2], [3, 4]]
    
    1.9.3p362 :006 > h = Hash[a]
    
     => {1=>2, 3=>4} 
    

提交回复
热议问题