Q:

Create groups (order of subarrays matter) from multiple arrays

I have three arrays. I want to combine the three of them, but order matters and I do NOT want to return all permutations. So for example:
STATE = [ 'Pennsylvania' ]
COUNTY = [ 'Bucks', 'Montgomery']
PROFESSION = ['Doctor', 'Firefighter', 'Teacher']

Expected output would be:
[
  ['Pennsylvania', 'Bucks', 'Doctor'],
  ['Pennsylvania', 'Bucks', 'Firefighter'],
  ['Pennsylvania', 'Bucks', 'Teacher'],

  ['Pennsylvania', 'Montgomery', 'Doctor'],
  ['Pennsylvania', 'Montgomery', 'Firefighter'],
  ['Pennsylvania', 'Montgomery', 'Teacher']
]

And that's it. State will always be first item. County will always be second item. Profession will always be third item and in that specific order. There should be no repeats.
The list of STATES and COUNTY and PROFESSION will continue to grow. But it will follow the same pattern.
These here are all wrong:
['Bucks', 'Pennsylvania', 'Doctor']
['Teacher', 'Montgomery', 'Pennsylvania']
['Pennsylvania', 'Bucks', 'Montgomery']

So what did I try? I thought perhaps using permutations would be a good tool. But as you guess, it created every possible combination. So I tried to use the lazy iterator to limit the results:
( STATE + COUNTY + PROFESSION ).permutation(3).lazy.first(10)
 => [["Pennsylvania", "Bucks", "Montgomery"], ["Pennsylvania", "Bucks", "Doctor"], ["Pennsylvania", "Bucks", "Firefighter"], ["Pennsylvania", "Bucks", "Teacher"], ["Pennsylvania", "Montgomery", "Bucks"], ["Pennsylvania", "Montgomery", "Doctor"], ["Pennsylvania", "Montgomery", "Firefighter"], ["Pennsylvania", "Montgomery", "Teacher"], ["Pennsylvania", "Doctor", "Bucks"], ["Pennsylvania", "Doctor", "Montgomery"]] 

But as you can see, the order I want is not preserved within in then subarray and also this is very buggy since each array will be of variable length and will grow.
What is a clean way to solve this problem in Ruby?

A:

What you're looking for is the product of the lists, not the combinations as the permutation function gives you. Your code will even return things like ["Teacher", "Firefighter", "Montgomery"] where you have two professions. Thankfully, Ruby arrays provide a product function:
STATE.product(COUNTY, PROFESSION)
=> [["Pennsylvania", "Bucks", "Doctor"], ["Pennsylvania", "Bucks", "Firefighter"], ["Pennsylvania", "Bucks", "Teacher"], ["Pennsylvania", "Montgomery", "Doctor"], ["Pennsylvania", "Montgomery", "Firefighter"], ["Pennsylvania", "Montgomery", "Teacher"]]

A product of lists A, B, and C will return all distinct lists of three elements that contain one element each from A, from B, and from C, in that order. Compare that to the permutation function you called, which takes your three lists concatenated together and gives you all combinations of three distinct elements from the unified list. When you concatenate, you throw away the division between the elements that you need.

