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

后端 未结 7 1773
走了就别回头了
走了就别回头了 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:56

    You could use inject to build an array of hashes.

    hash = { :a => ["val1", "val2"], :b => ["valb1", "valb2"] }
    array = hash.inject([]) do |pairs, pair|
      pairs << { pair[0] => pair[1] }
      pairs
    end
    array.inspect # => "[{:a=>["val1", "val2"]}, {:b=>["valb1", "valb2"]}]"
    

    Ruby documentation has a few more examples of working with inject.

提交回复
热议问题