Find all subsets of size N in an array using Ruby

Given an array ['a', 'b', 'c', 'd', 'e', 'f'], how would I get a list of all subsets containing two, three, and four elements?

I'm brand new to Ruby (transition from C #) and I'm not sure what the "Ruby Way" is.

+5
source share
2 answers

Mark Array # Combination

Then something like this:

2.upto(4) { |n| array.combination(n) }
+13
source

Tweaking basicxman a bit:

2.upto(4).flat_map { |n| array.combination(n).to_a }
#=> [["a", "b"], ["a", "c"], ["a", "d"], ..., ["c", "d", "e", "f"]]
+7
source

All Articles