LoginSignup
0
0

More than 5 years have passed since last update.

"配列のHash"を"Hashの配列"に変換する

Last updated at Posted at 2017-02-14

やりたいこと

{ A: [1, 2, 3], B: ['a', 'b', 'c'] }

[{A: 1, B: 'a'}, {A: 2, B: 'b'}, {A: 3, B: 'c'}]

の形に変換したい

やり方

    old_hash = { A: [1, 2, 3], B: ['a', 'b', 'c'] }

    new_hash = old_hash.map do |key, value|
      [[key] * value.length, value].transpose
    end.transpose.map(&:to_h)

    p new_hash # => [{:A=>1, :B=>"a"}, {:A=>2, :B=>"b"}, {:A=>3, :B=>"c"}]

もっと良い方法がありそう

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0