Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#repeated_combination

(::int size) { (::Array[Elem] combination) -> void } -> self
(::int size) -> ::Enumerator[::Array[Elem], self]
repeated_combination(size) {|combination| ... } → self
repeated_combination(size) → new_enumerator

With a block given, calls the block with each repeated combination of length size of the elements of self; each combination is an array; returns self. The order of the combinations is indeterminate.

If a positive integer argument size is given, calls the block with each size-tuple repeated combination of the elements of self. The number of combinations is (size+1)(size+2)/2.

Examples:

  • size is 1:

    Example
    c = []
    [0, 1, 2].repeated_combination(1) {|combination| c.push(combination) }
    c # => [[0], [1], [2]]
    
  • size is 2:

    Example
    c = []
    [0, 1, 2].repeated_combination(2) {|combination| c.push(combination) }
    c # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
    

If size is zero, calls the block once with an empty array.

If size is negative, does not call the block:

Example
[0, 1, 2].repeated_combination(-1) {|combination| fail 'Cannot happen' }

With no block given, returns a new Enumerator.

Related: see Methods for Combining.

See also #reject! #repeated_permutation #reject #replace also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0