2011-09-09 28 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' ... –

相關問題