Given a hash of arrays, how to create an array of hashes with each possible combo

Eddie

New Member
#1
Given a hash with values containing arrays of unequal lengths,
Mã:
{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?
Mã:
[
  {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.
 

Admin

Administrator
Thành viên BQT
#2
You try:
Mã:
keys = hash.keys
hash.values.inject(:product).map do |p|
  Hash[keys.zip(p.flatten)]
end
 
Top