arraysrubyruby-hash

Convert hash to array of hashes


I have hash, all its values are arrays, like this:

list = { letter:  ['a', 'b', 'c'],
         number:  ['one', 'two', 'three'],
         fruit:   ['apple', 'pear', 'kiwi'],
         car:     ['vw', 'mb', 'bmw'],
         state:   ['la', 'ny', 'fl'],
         color:   ['red', 'white', 'black'],
         tree:    ['oak', 'pine', 'maple'],
         animal:  ['cat', 'dog', 'rat'],
         clothes: ['tie', 'sock', 'glove'] }

In fact this hash could have more keys and values could be larger, but always sizes of every value are the same (in this case - three).

I want to convert this hash to array of hashes.

Each hash will have all keys of origin hash and respective value.

So finally I want to have:

list = [
  { letter: 'a', number: 'one', fruit: 'apple', car: 'vw', state: 'la',
    color: 'red', tree: 'oak', animal: 'cat', clothes: 'tie' },

  { letter: 'b', number: 'two', fruit: 'pear', car: 'mb', state: 'ny',
    color: 'white', tree: 'pine', animal: 'dog', clothes: 'sock' },

  { letter: 'c', number: 'three', fruit: 'kiwi', car: 'bmw', state: 'fl',
    color: 'black', tree: 'elm', animal: 'rat', clothes: 'glove' }
]

What's the best way to do it?


Solution

  • Leveraging Array#transpose and Array#to_h

    keys = list.keys
    list.values.transpose.map { |v| keys.zip(v).to_h }