Ruby | Array combination() operation
Array#combination() : combination() is an Array class method which invokes with a block yielding all combinations of length ‘n’ of elements of the array.
Syntax: Array.combination()
Parameter: Arrays in which we want elements to be invoked
Return: all combinations of length 'n' of elements of the array.
Code #1 : Example for combination() method
a = [ 1 , 2 , 56 , 23 ]
puts "combination a : #{a.combination(2).to_a}\n\n"
puts "combination a : #{a.combination(3).to_a}\n\n"
|
Output :
combination a : [[1, 2], [1, 56], [1, 23], [2, 56], [2, 23], [56, 23]]
combination a : [[1, 2, 56], [1, 2, 23], [1, 56, 23], [2, 56, 23]]
Code #2 : Example for combination() method
a = [[ 1 , 2 , 56 , 23 ],
[ 34 , 54 , 23 , 1 ]]
puts "collect a : #{a.combination(2).to_a}\n\n"
puts "collect a : #{a.combination(1).to_a}\n\n"
|
Output :
collect a : [[[1, 2, 56, 23], [34, 54, 23, 1]]]
collect a : [[[1, 2, 56, 23]], [[34, 54, 23, 1]]]
Last Updated :
10 Feb, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...