Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Ruby | Array combination() operation

  • Last Updated : 10 Feb, 2020

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]]]

My Personal Notes arrow_drop_up
Recommended Articles
Page :