We have the following datastructures:
{:a => ["val1", "val2"], :b => ["valb1", "valb2"], ...}
And I want to turn that into
[{:a => "val1", :b => "valb1"}, {:a => "val2", :b => "valb2"}, ...]
And then back into the first form. Anybody with a nice looking implementation?
This solution works with arbitrary numbers of values (val1, val2...valN):
My attempt, perhaps slightly more compact.
Should work in Ruby 1.9.3 or later.
Explanation:
First, 'combine' the corresponding values into 'rows'
Each iteration in the
map
block will produce one of these:and
Hash[]
will turn them into hashes:You could use
inject
to build an array of hashes.Ruby documentation has a few more examples of working with
inject
.Let's look closely what the data structure we are trying to convert between:
It is not diffculty to find
Format B
is the transpose ofFormat A
in essential , then we can come up with this solution:Using a functional approach (see Enumerable):
And back:
This will work assuming all the arrays in the original hash are the same size: