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

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

    Not sure if it's the best way, but this works:

    a = ["apple", 1, "banana", 2]
    m1 = {}
    for x in (a.length / 2).times
      m1[a[x*2]] = a[x*2 + 1]
    end
    
    b = [["apple", 1], ["banana", 2]]
    m2 = {}
    for x,y in b
      m2[x] = y
    end
    

提交回复
热议问题