How to get a combination of elements of an array in Ruby

Overview

The combination() method in Ruby takes an integer n as a parameter and produces combinations of length n for the elements of an array.

Syntax

array.combination(n)

Parameter

n: The length of the combination of elements.

Return value

This method returns all combinations of length n over the elements of the array.

# create an array
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d"]
# combine elements of the arrays
a = arr1.combination(2).to_a
b = arr2.combination(3).to_a
puts "#{a}" # combination in 2
puts "#{b}"

Explanation

  • Lines 2 and 3: We create arrays with 5 and 4 elements, respectively. arr1 has integer elements while arr2 has strings.

  • Line 6: We call combination() on arr1 to get all combinations of length 2.

  • Line 7: We call combination() on arr2 to get all combinations of length 3.

The combination() method returns enumerator. To get the array from the enumerator, we call the to_a method in lines 6 and 7.

Free Resources