Julien Genestoux - 7 months ago 13

Ruby Question

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?

Answer

This solution works with arbitrary numbers of values (val1, val2...valN):

```
{:a => ["val1", "val2"], :b => ["valb1", "valb2"]}.inject([]){|a, (k,vs)|
vs.each_with_index{|v,i| (a[i] ||= {})[k] = v}
a
}
# => [{:a=>"val1", :b=>"valb1"}, {:a=>"val2", :b=>"valb2"}]
[{:a=>"val1", :b=>"valb1"}, {:a=>"val2", :b=>"valb2"}].inject({}){|a, h|
h.each_pair{|k,v| (a[k] ||= []) << v}
a
}
# => {:a=>["val1", "val2"], :b=>["valb1", "valb2"]}
```