kid_drew - 7 months ago 43

Ruby Question

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!

Source (Stackoverflow)