Lets say i have the following arrays in ruby contained in an array and I don’t know how many arrays there will be or the length of them. An example below:
[["cat", "dog"],[1, 3, 5, 7],["morning", "afternoon", "evening"]]
what i want to do is have all combinations of results from picking 1 value from each array and returning it as an array of these combinations. Therefore, in the following example, there should be 2*4*3, or 24 possible unique results.
the result would be like :
result = [["cat", 1, "morning"], ["cat", 1, "afternoon"], ["dog", 5, "evening"] ...]
How would i go about doing this in ruby for a list of N arrays? I tried messing around with products and maps and injects but I cant get it working.
EDIT Since you made it clear that you’re dealing with not just three arrays
a1,a2anda3but an arrays of arrays, changing my solution to useproduct.Like this?Or with
flat_map:Wow, or just:
If you have several arrays (not just the fixed number of 3 in you first example),
then: