Array to Hash Ruby

后端 未结 9 490
无人及你
无人及你 2021-01-29 17:43

Okay so here\'s the deal, I\'ve been googling for ages to find a solution to this and while there are many out there, they don\'t seem to do the job I\'m looking for.

Ba

9条回答
  •  余生分开走
    2021-01-29 18:24

    You could try like this, for single array

    irb(main):019:0> a = ["item 1", "item 2", "item 3", "item 4"]
      => ["item 1", "item 2", "item 3", "item 4"]
    irb(main):020:0> Hash[*a]
      => {"item 1"=>"item 2", "item 3"=>"item 4"}
    

    for array of array

    irb(main):022:0> a = [[1, 2], [3, 4]]
      => [[1, 2], [3, 4]]
    irb(main):023:0> Hash[*a.flatten]
      => {1=>2, 3=>4}
    

提交回复
热议问题