Julien Genestoux Julien Genestoux - 1 year ago 55
Ruby Question

Turning a Hash of Arrays into an Array of Hashes in Ruby

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 Source

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=>"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=>["val1", "val2"], :b=>["valb1", "valb2"]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download