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

后端 未结 11 2032
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    If the numeric values are seq indexes, then we could have simpler ways... Here's my code submission, My Ruby is a bit rusty

       input = ["cat", 1, "dog", 2, "wombat", 3]
       hash = Hash.new
       input.each_with_index {|item, index|
         if (index%2 == 0) hash[item] = input[index+1]
       }
       hash   #=> {"cat"=>1, "wombat"=>3, "dog"=>2}
    

提交回复
热议问题