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#combination

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

Calls the block, if given, with combinations of elements of self; returns self. The order of combinations is indeterminate.

When a block and an in-range positive Integer argument n (0 < n <= self.size) are given, calls the block with all n-tuple combinations of self.

Example:

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

Output:

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

Another example:

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

Output:

Example
[0, 1, 2]

When n is zero, calls the block once with a new empty Array:

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

Output:

Example
[]

When n is out of range (negative or larger than self.size), does not call the block:

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

Returns a new Enumerator if no block given:

Example
a = [0, 1, 2]
a.combination(2) # => #<Enumerator: [0, 1, 2]:combination(2)>
See also #collect! #compact #collect #compact! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1