7

In order to compute the cartesian product in Ruby, one can use Array#product, how is the syntax if I have an array of arrays and want to compute the product?

[[1,2],[3,4],[5,6]] => [[1,3,5], [2,3,5], ...]

I am not sure, because in the Ruby documentation the product method is defined with an arbitrary number of arguments, so simply passing my arrays of arrays as an argument, like that:

[].product(as) => [

does not suffice. How can I solve this?

2 Answers 2

11

The method takes multiple arguments, but not an array containing arguments. So you have to use it in this way:

[1,2].product [3,4], [5,6]

If as is your array of arrays, you will have to "splat" it like this:

as[0].product(*as[1..-1])
Sign up to request clarification or add additional context in comments.

5 Comments

[].product(*as) always produces an empty array, which is a shame, as it would be nice to do what the OP was asking without having to draw out one of the arrays as the first object.
There's a discussion related to this here, where some people argued for class methods like Array.product(*arrays). I think this would have been useful, but I guess it didn't happen.
(as[0]).product(*as.drop(1)) is a version that works
Mateusz Konieczny, thank you for the improvement! I only varied the style a little.
@reducingactivity: ...and if as can be mutated, one could write as.shift.product(*as).
3

Closest notation I've got is:

:product.to_proc.call(*as)

# shorthand
:product.to_proc.(*as)
:product.to_proc[*as]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.