2010-08-05 9 views
7

Ich bin auf der Suche nach allen Kombinationen von einzelnen Elementen aus einer variablen Anzahl von Arrays. Wie mache ich das in Ruby?Das Produkt einer variablen Anzahl von Ruby-Arrays finden

Gegeben zwei Arrays, kann ich Array.product wie folgt verwenden:

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"]] 

Wie könnte dieser Code funktionieren, wenn Gruppen eine variable Anzahl von Arrays enthält?

Antwort

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

Wow, danke. Könntest du, oder jemand, erklären, wie das funktioniert? –

+2

Eine Erklärung dessen, was dies tatsächlich tut, wäre auch hilfreich und führt wahrscheinlich zu einem besseren Design des OP-Codes ... – jtbandes

+1

@Ollie: 'Array # product' kann mehrere Arrays als Argumente annehmen, also macht dies im Grunde nur' Gruppen [0] .product (groups [1], groups [2], ...) ' – jtbandes

Verwandte Themen