2010-08-05 43 views
7

我期待從可變數量的數組中找到單個項目的所有組合。我如何在Ruby中執行此操作?查找可變數量的Ruby數組的產品

給定兩個數組,我可以使用Array.product這樣的:

groups = [] 
groups[0] = ["hello", "goodbye"] 
groups[1] = ["world", "everyone"] 

combinations = groups[0].product(groups[1]) 

puts combinations.inspect 
# [["hello", "world"], ["hello", "everyone"], ["goodbye", "world"], ["goodbye", "everyone"]] 

怎麼能當組包含可變數量的陣列此代碼的工作?

回答

13
groups = [ 
    %w[hello goodbye], 
    %w[world everyone], 
    %w[here there] 
] 

combinations = groups.first.product(*groups.drop(1)) 

p combinations 
# [ 
# ["hello", "world", "here"], 
# ["hello", "world", "there"], 
# ["hello", "everyone", "here"], 
# ["hello", "everyone", "there"], 
# ["goodbye", "world", "here"], 
# ["goodbye", "world", "there"], 
# ["goodbye", "everyone", "here"], 
# ["goodbye", "everyone", "there"] 
# ] 
+1

哇,謝謝。你可以或者可以解釋一下這是如何工作的嗎? – 2010-08-05 23:37:36

+2

對這個實際做的解釋也會有所幫助,並且可能會導致更好的OP代碼設計... – jtbandes 2010-08-05 23:38:07

+1

@Ollie:Array#product可以將多個數組作爲參數,所以這只是基本上做了組[0] .product(groups [1],groups [2],...)' – jtbandes 2010-08-05 23:38:44