Compute a massive array on an array of arrays
To compute Cartesian product in Ruby can be used Array#product
as 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'm not sure, because the Ruby documentation product
defines a method with an arbitrary number of arguments, so just pass arrays of arrays as an argument, like this:
[].product(as) => [
lacks. How can I solve this?
+3
Max rhan
source
to share
2 answers
The method accepts multiple arguments, but not an array containing the arguments. Therefore, you should use it this way:
[1,2].product [3,4], [5,6]
If as
is your array of arrays, you will have to "split" it like this:
as[0].product(*as[1..-1])
+5
J -_- L
source
to share
Nearest notation:
:product.to_proc.call(*as)
# shorthand
:product.to_proc.(*as)
0
snipsnipsnip
source
to share