IronCode IronCode - 1 year ago 85
Ruby Question

Get first element of nested array for hash key

Supposing I have an array that looks like:

[["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 Source { |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| [a.first, a.drop(1)] }]
#=> {"str1"=>["val1", "val2"], "str2"=>["val1", "val2", "val3"]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download