5 给定数组['a', 'b', 'c', 'd', 'e', 'f'],我将如何得到包含2,3,4个元素的所有子集的列表?使用Ruby查找数组中大小为N的所有子集 我对Ruby很陌生(从C#移动过来),不确定'Ruby Way'是什么。 来源 2011-09-09 KevDog
13 退房Array#combination 然后是这样的: 2.upto(4) { |n| array.combination(n) } 来源 2011-09-09 00:41:25 basicxman +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"]] 来源 2011-09-09 08:22:28 tokland +0 你认为扁平化的优点是什么? – KevDog +0 @KevDog:你问了一个“所有子集的列表”,所以它似乎适合返回一个扁平数组。这只是一个细节,我想说“映射”upto更重要。 – tokland +1 更好地使用'flat_map' ... –
真棒!我不知道图书馆那么深。 – KevDog
您必须收集块的输出:2.upto(4).map {...} – tokland
即使这并不会创建一个简单的枚举,当然,但列表的列表。 –