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

后端 未结 7 1737
走了就别回头了
走了就别回头了 2020-12-30 07:19

We have the following datastructures:

{:a => [\"val1\", \"val2\"], :b => [\"valb1\", \"valb2\"], ...}

And I want to turn that into

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 08:06

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

提交回复
热议问题