Julien Genestoux Julien Genestoux - 6 months ago 6
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

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"]}