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 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}"
Explanation
-
Lines 2 and 3: We create arrays with 5 and 4 elements, respectively.
arr1has integer elements whilearr2has strings. -
Line 6: We call
combination()onarr1to get all combinations of length2. -
Line 7: We call
combination()onarr2to get all combinations of length3.
The combination() method returns enumerator. To get the array from the enumerator, we call the to_a method in lines 6 and 7.