Open In App

Ruby | Array combination() operation

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Ruby code for combination() method
  
# declaring array
a = [1, 2, 56, 23]
  
# combination of length 2
puts "combination a : #{a.combination(2).to_a}\n\n"
  
# combination of length 3
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




# Ruby code for combination() method
  
# declaring array
a = [[1, 2, 56, 23],
    [34, 54, 23, 1]]
  
# combination of length 2
puts "collect a : #{a.combination(2).to_a}\n\n"
  
# combination of length 1
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
Previous
Next
Share your thoughts in the comments
Similar Reads