Given a hash with values containing arrays of unequal lengths,
{a: [1, 2, 3], b: [1, 2], c: [1]}
is it possible to create an array of hashes containing the same keys, of all permutations of single values like the following without resorting to nesting multiple loops?
[
{a: 1, b: 1, c: 1},
{a: 1, b: 2, c: 1},
{a: 2, b: 1, c: 1},
{a: 2, b: 2, c: 1},
{a: 3, b: 2, c: 1},
{a: 3, b: 2, c: 1}
]
We accomplish this using nested each
loops for each key, but this looks nasty at a large scale. Actual data contain many more keys.
keys = hash.keys
hash.values.inject(:product).map do |p|
Hash[keys.zip(p.flatten)]
end
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加