Turning a Hash of Arrays into an Array of Hashes i

2019-02-05 01:17发布

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?

标签: ruby arrays hash
7条回答
祖国的老花朵
2楼-- · 2019-02-05 01:59
m = {}
a,b = Array(h).transpose
b.transpose.map { |y| [a, y].transpose.inject(m) { |m,x| m.merge Hash[*x] }}
查看更多
登录 后发表回答