2014-10-10 93 views

回答

7

使用Array#product,你可以得到笛卡爾乘積:

colors = ['yellow', 'green'] 
shirts = ['s','m','xl','xxl'] 
colors.product(shirts).map { |c, s| "#{c}_#{s}" } 
# => ["yellow_s", "yellow_m", "yellow_xl", "yellow_xxl", 
#  "green_s", "green_m", "green_xl", "green_xxl"] 

colors.product(shirts).map { |e| e.join("_") } 
# => ["yellow_s", "yellow_m", "yellow_xl", "yellow_xxl", 
#  "green_s", "green_m", "green_xl", "green_xxl"] 
+3

或者'colors.product(shirts).map {| e | e.join(「_」)}' – Candide 2014-10-10 12:37:01

+0

@Cideide,謝謝您提供替代方案。我將它添加到答案中。 – falsetru 2014-10-10 12:38:09

+0

謝謝你們。我不知道這種方法。 – 2014-10-10 12:40:22

0

我用這個方法。

colors = ['green', 'yellow'] 
shirts = ['s','m', 'xl', 'l'] 
selection = [] 
x = 0 
while x < shirts.length 
    selections.push(colors.map{|c|c + "_" + shirts[x]}) 
    x += 1 
end 
selections.flatten! 

=> ['yellow_s', 'green_s', 'yellow_m', 'green_m', 'yellow_xl', 'green_xl', 'yellow_xxl', 'green_xxl'] 
相關問題