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

后端 未结 7 1787
走了就别回头了
走了就别回头了 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 07:53

    My attempt, perhaps slightly more compact.

    h = { :a => ["val1", "val2"], :b => ["valb1", "valb2"] }
    
    h.values.transpose.map { |s| Hash[h.keys.zip(s)] }
    

    Should work in Ruby 1.9.3 or later.


    Explanation:

    First, 'combine' the corresponding values into 'rows'

    h.values.transpose
    # => [["val1", "valb1"], ["val2", "valb2"]] 
    

    Each iteration in the map block will produce one of these:

    h.keys.zip(s)
    # => [[:a, "val1"], [:b, "valb1"]]
    

    and Hash[] will turn them into hashes:

    Hash[h.keys.zip(s)]
    # => {:a=>"val1", :b=>"valb1"}      (for each iteration)
    

提交回复
热议问题