Array#permutation
arr.permutation(n) { |p| block } Returns:
Enumerator or Array · Updated March 13, 2026 · Array Methods arrays enumerable combinations permutations
Array#permutation generates all possible ordered arrangements of array elements of a given size. This method is essential for solving combinatorial problems, generating test cases, and exploring mathematical relationships in your data.
Syntax
array.permutation(n) { |p| block }
Returns an Enumerator when called without a block, allowing you to chain other Enumerable methods or convert to an array.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | Integer | Required | The size of each permutation to generate |
Examples
Basic usage
# Generate all permutations of 2 elements
[1, 2, 3].permutation(2).to_a
# => [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
With a block
# Using a block with permutation
[1, 2].permutation(2) do |p|
puts "Permutation: \#{p.join(, )}"
end
# Permutation: 1, 2
# Permutation: 2, 1
Practical examples
# Find all possible orders for scheduling 3 tasks
tasks = [:design, :code, :test]
schedules = tasks.permutation(3).to_a
# => [[:design, :code, :test], [:design, :test, :code],
# [:code, :design, :test], [:code, :test, :design],
# [:test, :design, :code], [:test, :code, :design]]
Common Patterns
Generating all possible orderings
letters = [a, b, c]
letters.permutation(2).to_a
# => [["a", "b"], ["a", "c"], ["b", "a"], ["b", "c"], ["c", "a"], ["c", "b"]]
Finding unique arrangements
# Get all 3-letter arrangements from a set of letters
[A, B, C, D].permutation(3).to_a
# Returns 24 possible ordered arrangements
Error Cases
# Negative size raises ArgumentError
[1, 2, 3].permutation(-1)
# => ArgumentError: negative permutation size (-1)
# Size greater than array length returns empty enumerator
[1, 2].permutation(5).to_a
# => []
# Size equal to zero returns single empty array
[1, 2, 3].permutation(0).to_a
# => [[]]