The combination()
method in Ruby
takes an integer n
as a parameter and produces combinations of length n
for the elements of an array.
array.combination(n)
n
: The length of the combination of elements.
This method returns all combinations of length n
over the elements of the array.
# create an arrayarr1 = [1, 2, 3, 4, 5]arr2 = ["a", "b", "c", "d"]# combine elements of the arraysa = arr1.combination(2).to_ab = arr2.combination(3).to_aputs "#{a}" # combination in 2puts "#{b}"
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.