Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#product

array.product(*other_arrays) → new_array
array.product(*other_arrays) {|combination| ... } → self

Computes and returns or yields 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.

When no block is given, returns the combinations as an Array of Arrays:

Example
a = [0, 1, 2]
a1 = [3, 4]
a2 = [5, 6]
p = a.product(a1)
p.size # => 6 # a.size * a1.size
p # => [[0, 3], [0, 4], [1, 3], [1, 4], [2, 3], [2, 4]]
p = a.product(a1, a2)
p.size # => 12 # a.size * a1.size * a2.size
p # => [[0, 3, 5], [0, 3, 6], [0, 4, 5], [0, 4, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]]

If any argument is an empty Array, returns an empty Array.

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

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

When a block is given, yields each combination as an Array; returns self:

Example
a.product(a1) {|combination| p combination }

Output:

Example
[0, 3]
[0, 4]
[1, 3]
[1, 4]
[2, 3]
[2, 4]

If any argument is an empty Array, does not call the block:

Example
a.product(a1, a2, []) {|combination| fail 'Cannot happen' }

If no argument is given, yields each element of self as a 1-element Array:

Example
a.product {|combination| p combination }

Output:

Example
[0]
[1]
[2]
See also #prepend #push #pop #rassoc also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1