@superacidjax That’s a fascinating problem! Because you’re using nested `each`

s to build a flattened array, `Array#flat_map`

immediately comes to mind. To get it to work for arbitrary sizes, I’m guessing you could combine that with `Array#inject`

.

*But… turns out Ruby already has you covered!*

## Cartesian products

What you are asking for is called the cartesian product and it’s already built in with `Array#product`

.

For example:

```
[0, 1].product([0, 1])
# => [[0, 0], [0, 1], [1, 0], [1, 1]]
```

Notice that this gives us all possible 2-bit numbers, from 00-11

You can give `Array#product`

any number of arrays:

```
[0, 1].product([0, 1], [0, 1])
# => [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
```

Notice that this gives us all the possible 3-bit numbers, from 000-111.

## Your problem

Looking at your exact problem:

```
["A", "no A"].product(["B", "no B"], ["C", "no C"], ["D", "no D"])
=> [["A", "B", "C", "D"],
["A", "B", "C", "no D"],
["A", "B", "no C", "D"],
["A", "B", "no C", "no D"],
["A", "no B", "C", "D"],
["A", "no B", "C", "no D"],
["A", "no B", "no C", "D"],
["A", "no B", "no C", "no D"],
["no A", "B", "C", "D"],
["no A", "B", "C", "no D"],
["no A", "B", "no C", "D"],
["no A", "B", "no C", "no D"],
["no A", "no B", "C", "D"],
["no A", "no B", "C", "no D"],
["no A", "no B", "no C", "D"],
["no A", "no B", "no C", "no D"]]
```

gives you all the possible combinations from “ABCD” to “noA noB noC noD”

## Generic solution

We can make this work with any generic array of arrays by leveraging the splat `*`

operator.

```
def combinations(arrays)
first, *rest = arrays
first.product(*rest)
end
```

Then we can say:

```
arrays_to_combine = [["A", "no A"], ["B", "no B"], ["C", "no C"], ["D", "no D"]]
combinations(arrays_to_combine)
=> [["A", "B", "C", "D"],
["A", "B", "C", "no D"],
["A", "B", "no C", "D"],
["A", "B", "no C", "no D"],
["A", "no B", "C", "D"],
["A", "no B", "C", "no D"],
["A", "no B", "no C", "D"],
["A", "no B", "no C", "no D"],
["no A", "B", "C", "D"],
["no A", "B", "C", "no D"],
["no A", "B", "no C", "D"],
["no A", "B", "no C", "no D"],
["no A", "no B", "C", "D"],
["no A", "no B", "C", "no D"],
["no A", "no B", "no C", "D"],
["no A", "no B", "no C", "no D"]]
```