2014-10-28 204 views
1

元件的每一個組合我有三個紅寶石數組:兩個紅寶石陣列

color = ['blue', 'green', 'yellow'] 
names = ['jack', 'jill'] 
combination = [] 

我需要插入combination陣列以下級聯:

FOR EACH names value: [name value] + " wants " + [color value] 

所以結果將是:

combination = ['jack wants blue','jack wants green','jack wants yellow','jill wants blue','jill wants green','jill wants yellow'] 

我無法弄清楚如何做到這一點。我試過這個,開始用,但無濟於事:

name.each do |name| 
    puts "#{name} wants #{color}" 
end 
+1

是什麼在選擇答案匆忙?快速選擇往往會阻礙其他的答案,對於那些仍然在準備答案的人來說,當綠黨人閃過時,他們是一件壞事。 – 2014-10-28 16:21:57

+0

@CarySwoveland - 我很抱歉,那當然不是我的意圖。我測試過它能夠滿足我的需求,我認爲如果我快速選擇,它會受益更多。 – HKBR1907 2014-10-29 09:00:51

+0

您不必道歉。對於在選擇答案之前應該等待多長時間有不同的意見。那些剛剛接觸SO的人並沒有真正考慮過它,並且急於表示感謝他們給出了一個好的答案。順便說一句,我並不是暗示我正在準備答案。 (我沒有什麼有用的補充。) – 2014-10-29 15:54:47

回答

8

您可以使用Array#product

names = ['jack', 'jill'] 
colors = ['blue', 'green', 'yellow'] 

names.product(colors).map { |name, color| "#{name} wants #{color}" } 
#=> ["jack wants blue", "jack wants green", "jack wants yellow", "jill wants blue", "jill wants green", "jill wants yellow"] 
+1

或'names.product(colors).map {| arr | arr.join(「want」)}'如果你不想摔打和插入。 – 2014-10-28 16:02:14

0
names = ['jack', 'jill'] 
colors = ['blue', 'green', 'yellow'] 
# Note - renamed to "colors" plural 
names.collect { |name| colors.collect { |color| "#{name} wants #{color}" } }.flatten 

=> ["jack wants blue", "jack wants green", "jack wants yellow", "jill wants blue", "jill wants green", "jill wants yellow"] 
2

插值將工作在其他的答案,但我喜歡字符串格式更好像這樣的情況。 freeze方法用於優化。它也可以沒有它。

names.product(colors).map{|a| "%s wants %s".freeze % a} 
+1

+1,如果順序不重要,我會使用它,例如'「%s與%s」' – Stefan 2014-10-28 16:52:56