Wednesday, June 24, 2015

Generate all combinations of a given length for a list of items

In Ruby 2.2.2:

 a = [1,2,3,4]
 a.combination(2)
 => # 

We need to call to_a on this enumerator:

 a = ['A', 'B', 'C', 'D']
 => ["A", "B", "C", "D"]
> a.combination(2).to_a
 => [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]