Skip to content
instance method

Array#product

() -> ::Array[[ Elem ]]
[X] (::Array[X] other_ary) -> ::Array[[ Elem, X ]]
[X, Y] (::Array[X] other_ary1, ::Array[Y] other_ary2) -> ::Array[[ Elem, X, Y ]]
[U] (*::Array[U] other_arys) -> ::Array[::Array[Elem | U]]
product(*other_arrays) → new_array
product(*other_arrays) {|combination| ... } → self

Computes all combinations of elements from all the arrays, including both self and other_arrays:

  • The number of combinations is the product of the sizes of all the arrays, including both self and other_arrays.

  • The order of the returned combinations is indeterminate.

With no block given, returns the combinations as an array of arrays:

Example
p = [0, 1].product([2, 3])
# => [[0, 2], [0, 3], [1, 2], [1, 3]]
p.size # => 4
p = [0, 1].product([2, 3], [4, 5])
# => [[0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3,...
p.size # => 8

If self or any argument is empty, returns an empty array:

Example
[].product([2, 3], [4, 5]) # => []
[0, 1].product([2, 3], []) # => []

If no argument is given, returns an array of 1-element arrays, each containing an element of self:

Example
a.product # => [[0], [1], [2]]

With a block given, calls the block with each combination; returns self:

Example
p = []
[0, 1].product([2, 3]) {|combination| p.push(combination) }
p # => [[0, 2], [0, 3], [1, 2], [1, 3]]

If self or any argument is empty, does not call the block:

Example
[].product([2, 3], [4, 5]) {|combination| fail 'Cannot happen' }
# => []
[0, 1].product([2, 3], []) {|combination| fail 'Cannot happen' }
# => [0, 1]

If no argument is given, calls the block with each element of self as a 1-element array:

Example
p = []
[0, 1].product {|combination| p.push(combination) }
p # => [[0], [1]]

Related: see Methods for Combining.

See also #prepend #push #pop #rassoc also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0