2010-08-05 4 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

와우, 감사합니다. 당신이나 다른 누군가가 어떻게 작동하는지 설명 할 수 있습니까? –

+2

이것이 실제로하는 일에 대한 설명도 도움이 될 것이고, 아마도 OP 코드의 더 나은 디자인으로 이어질 것입니다 ... – jtbandes

+1

@Ollie :'Array # product'는 여러 배열을 인수로 취할 수 있습니다. 그래서 이것은 기본적으로'groups '0 '.product (groups [1], groups [2], ...)' – jtbandes

관련 문제