Array to Hash Ruby

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

    a = ["item 1", "item 2", "item 3", "item 4"]
    h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }
    

    That's it. The * is called the splat operator.

    One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."

    So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Łukasz Niemier (also in the comments) offers this method for large data sets:

    h = Hash[a.each_slice(2).to_a]
    

提交回复
热议问题