Array to Hash Ruby

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

    All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

    Let's look at:

    a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]
    

    You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

    Hash[*a]
    => {"item 1"=>"item 5", "item 3"=>"item 4"}
    

    All of the methods, including the reduce(&:merge!) result in the same removal.

    It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

    {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}
    

    The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

    result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
    a.each_slice(2) {|k,v| result[k] << v }
    a
    => {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}
    

    It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

提交回复
热议问题