Array#combination

arr.combination(n) { |c| block }
Returns: Enumerator or Array · Updated March 13, 2026 · Array Methods
arrays enumerable combinations permutations

Array#combination generates all possible unordered 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.combination(n) { |c| block }

Returns an Enumerator when called without a block, allowing you to chain other Enumerable methods or convert to an array.

Parameters

ParameterTypeDefaultDescription
nIntegerRequiredThe size of each combination to generate

Examples

Basic usage

# Generate all combinations of 2 elements
[1, 2, 3].combination(2).to_a
# => [[1, 2], [1, 3], [2, 3]]

With a block

# Using a block with combination
[1, 2, 3].combination(2) do |c|
  puts "Combination: #{c.join(', ')}"
end
# Combination: 1, 2
# Combination: 1, 3
# Combination: 2, 3

Practical examples

# Generate all possible teams of 2 from a list of players
players = ["Alice", "Bob", "Charlie", "Diana"]
teams = players.combination(2).to_a
# => [["Alice", "Bob"], ["Alice", "Charlie"], ["Alice", "Diana"],
#     ["Bob", "Charlie"], ["Bob", "Diana"], ["Charlie", "Diana"]]

Common Patterns

Password cracking simulation

characters = ['a', 'b', 'c']
characters.combination(2).each do |combo|
  puts combo.join
end
# ab
# ac
# bc

Lottery number generation

numbers = (1..49).to_a
winning_numbers = numbers.combination(6).first

Error Cases

# Negative size raises ArgumentError
[1, 2, 3].combination(-1)
# => ArgumentError: negative combination size (-1)

# Size greater than array length returns empty enumerator
[1, 2].combination(5).to_a
# => []

# Size equal to zero returns single empty array
[1, 2, 3].combination(0).to_a
# => [[]]

See Also