Array to Hash Ruby

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

    a = ["item 1", "item 2", "item 3", "item 4"]
    Hash[ a.each_slice( 2 ).map { |e| e } ]
    

    or, if you hate Hash[ ... ]:

    a.each_slice( 2 ).each_with_object Hash.new do |(k, v), h| h[k] = v end
    

    or, if you are a lazy fan of broken functional programming:

    h = a.lazy.each_slice( 2 ).tap { |a|
      break Hash.new { |h, k| h[k] = a.find { |e, _| e == k }[1] }
    }
    #=> {}
    h["item 1"] #=> "item 2"
    h["item 3"] #=> "item 4"
    

提交回复
热议问题