Skip to content

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

instance method

Array#repeated_combination

array.repeated_combination(n) {|combination| ... } → self
array.repeated_combination(n) → new_enumerator

Calls the block with each repeated combination of length n of the elements of self; each combination is an Array; returns self. The order of the combinations is indeterminate.

When a block and a positive Integer argument n are given, calls the block with each n-tuple repeated combination of the elements of self. The number of combinations is (n+1)(n+2)/2.

n = 1:

Example
a = [0, 1, 2]
a.repeated_combination(1) {|combination| p combination }

Output:

Example
[0]
[1]
[2]

n = 2:

Example
a.repeated_combination(2) {|combination| p combination }

Output:

Example
[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]

If n is zero, calls the block once with an empty Array.

If n is negative, does not call the block:

Example
a.repeated_combination(-1) {|combination| fail 'Cannot happen' }

Returns a new Enumerator if no block given:

Example
a = [0, 1, 2]
a.repeated_combination(2) # => #<Enumerator: [0, 1, 2]:combination(2)>

Using Enumerators, it’s convenient to show the combinations and counts for some values of n:

Example
e = a.repeated_combination(0)
e.size # => 1
e.to_a # => [[]]
e = a.repeated_combination(1)
e.size # => 3
e.to_a # => [[0], [1], [2]]
e = a.repeated_combination(2)
e.size # => 6
e.to_a # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
See also #reject! #repeated_permutation #reject #replace also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0