Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute array product on an array of arrays

Tags:

arrays

ruby

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?

like image 599
Max Rhan Avatar asked Feb 03 '13 01:02

Max Rhan


2 Answers

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])
like image 85
J-_-L Avatar answered Sep 20 '22 08:09

J-_-L


Closest notation I've got is:

:product.to_proc.call(*as)

# shorthand
:product.to_proc.(*as)
:product.to_proc[*as]
like image 31
snipsnipsnip Avatar answered Sep 20 '22 08:09

snipsnipsnip