两个Ruby数组中的每个元素组合

时间:2014-10-28 15:51:31

标签: ruby

我有三个Ruby数组:

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

3 个答案:

答案 0 :(得分: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 :(得分:2)

插值可以像其他答案一样工作,但在这种情况下,我更喜欢字符串格式。 freeze方法用于优化。没有它也可以。

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

答案 2 :(得分: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"]