Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#permutation

(?::int n) -> ::Enumerator[::Array[Elem], ::Array[Elem]]
(?::int n) { (::Array[Elem] p) -> void } -> ::Array[Elem]
permutation(count = self.size) {|permutation| ... } → self
permutation(count = self.size) → new_enumerator

Iterates over permutations of the elements of self; the order of permutations is indeterminate.

With a block and an in-range positive integer argument count (0 < count <= self.size) given, calls the block with each permutation of self of size count; returns self:

Example
a = [0, 1, 2]
perms = []
a.permutation(1) {|perm| perms.push(perm) }
perms # => [[0], [1], [2]]

perms = []
a.permutation(2) {|perm| perms.push(perm) }
perms # => [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]

perms = []
a.permutation(3) {|perm| perms.push(perm) }
perms # => [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]

When count is zero, calls the block once with a new empty array:

Example
perms = []
a.permutation(0) {|perm| perms.push(perm) }
perms # => [[]]

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

Example
a.permutation(-1) {|permutation| fail 'Cannot happen' }
a.permutation(4) {|permutation| fail 'Cannot happen' }

With no block given, returns a new Enumerator.

Related: Methods for Iterating.

See also #pack #pop #one? #prepend also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0