IBG
IBG

Reputation: 465

Iterating hash of arrays to create an array of array

Suppose I have a hash

@attribute_type = {
  typeA: ['a', 'b', 'c'],
  typeB: ['1', '2', '3'],
  typeC: ['9', '8', '7']
}

I want to iterate over the values so I can create an array having all distinct possible combinations of the three arrays, for example:

['a', '1', '9'], ['a', '1', '8'], ['a', '1', '7'], ['a', '2', '9'], ...

Is this possible?

Upvotes: 0

Views: 76

Answers (2)

iGian
iGian

Reputation: 11183

My 2 cents.

Pretty the same as Cary Swoveland, but just one line:

h.values.first.product(*h.values.drop(1))

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

h = { :typeA=>['a','b','c'], :typeB=>['1','2','3'], :typeC=>['9','8','7'] }

first, *rest = h.values
  #=> [["a", "b", "c"], ["1", "2", "3"], ["9", "8", "7"]]
first.product(*rest)
  #=> [["a", "1", "9"], ["a", "1", "8"], ["a", "1", "7"],
  #    ["a", "2", "9"], ["a", "2", "8"], ["a", "2", "7"],
  #    ["a", "3", "9"], ["a", "3", "8"], ["a", "3", "7"],
  #    ["b", "1", "9"], ["b", "1", "8"], ["b", "1", "7"],
  #    ["b", "2", "9"], ["b", "2", "8"], ["b", "2", "7"],
  #    ["b", "3", "9"], ["b", "3", "8"], ["b", "3", "7"],
  #    ["c", "1", "9"], ["c", "1", "8"], ["c", "1", "7"],
  #    ["c", "2", "9"], ["c", "2", "8"], ["c", "2", "7"],
  #    ["c", "3", "9"], ["c", "3", "8"], ["c", "3", "7"]]

See Array#product.

Upvotes: 11

Related Questions