IronCode IronCode - 1 month ago 9
Ruby Question

Get first element of nested array for hash key

Supposing I have an array that looks like:

[
[["str1"],["val1"],["val2"]],
[["str2"], ["val1"], ["val2"], ["val3"]]
]


Is there a way for me to get a Hash that looks like:

{
"str1" => [["val1"],["val2"]],
"str2" => [["val1"],["val2"],["val3"]]
}

Answer
a.map { |a| [a.first.first, a.drop(1)] }.to_h
# or
a.each_with_object({}) {|a, h| h[a.first.first] = a.drop(1) }
#=> {
#     "str1"=>[["val1"], ["val2"]],
#     "str2"=>[["val1"], ["val2"], ["val3"]]
#   }

If you do not want to have each element in a separate array:

Hash[a.map(&:flatten).map { |a| [a.first, a.drop(1)] }]
#=> {"str1"=>["val1", "val2"], "str2"=>["val1", "val2", "val3"]}