Array to Hash Ruby

后端 未结 9 475
无人及你
无人及你 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:26

    Enumerator includes Enumerable. Since 2.1, Enumerable also has a method #to_h. That's why, we can write :-

    a = ["item 1", "item 2", "item 3", "item 4"]
    a.each_slice(2).to_h
    # => {"item 1"=>"item 2", "item 3"=>"item 4"}
    

    Because #each_slice without block gives us Enumerator, and as per the above explanation, we can call the #to_h method on the Enumerator object.

提交回复
热议问题