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

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

When invoked with a block, yield all permutations of elements of self; returns self. The order of permutations 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 permutations of self.

Example:

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

Output:

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

Another example:

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

Output:

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

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

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

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.permutation(-1) {|permutation| fail 'Cannot happen' }
a.permutation(4) {|permutation| fail 'Cannot happen' }

When a block given but no argument, behaves the same as a.permutation(a.size):

Example
a = [0, 1, 2]
a.permutation {|permutation| p permutation }

Output:

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

Returns a new Enumerator if no block given:

Example
a = [0, 1, 2]
a.permutation # => #<Enumerator: [0, 1, 2]:permutation>
a.permutation(2) # => #<Enumerator: [0, 1, 2]:permutation(2)>
See also #pack #pop #one? #prepend also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0