2011-09-09 27 views

回答

13

退房Array#combination

然后是这样的:

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

真棒!我不知道图书馆那么深。 – KevDog

+1

您必须收集块的输出:2.upto(4).map {...} – tokland

+1

即使这并不会创建一个简单的枚举,当然,但列表的列表。 –

7

扭捏basicxman是一点点:

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

你认为扁平化的优点是什么? – KevDog

+0

@KevDog:你问了一个“所有子集的列表”,所以它似乎适合返回一个扁平数组。这只是一个细节,我想说“映射”upto更重要。 – tokland

+1

更好地使用'flat_map' ... –

相关问题