kid_drew kid_drew - 9 days ago 6
Ruby Question

Rails - multi-dimensional array with labels to array of hash

I have a multi-dimensional array where the first row contains the value labels:

[
['a','b','c'],
[1,2,3],
[4,5,6]
]


I would like to convert that array to an array of hashes where the labels are the indexes in each element:

[
{'a' => 1, 'b' => 2, 'c' => 3},
{'a' => 4, 'b' => 5, 'c' => 6}
]


What's the quickest way to do that in Ruby/Rails?

Answer

This is one way to convert your array into an array of hashes where the first sub array acts as the set of keys:

arr = [
       ['a', 'b', 'c'],
       [1, 2, 3],
       [4, 5, 6]
      ]

labels = arr.shift

arr.map { |sub_arr| Hash[labels.zip(sub_arr)] }

# => [{'a' => 1, 'b' => 2, 'c' => 3}, {'a' => 4, 'b' => 5, 'c' => 6}]

Hope it helps!