将一个数组的每个元素连接到ruby中其他数组的每个元素

时间:2014-10-10 12:28:41

标签: ruby-on-rails ruby arrays ruby-on-rails-3

我有两个数组,我可以加入它们循环这两个数组。但有更好的方法吗?

colors = ['yellow', 'green']
shirts = ['s','m','xl','xxl']

需要输出:

output = ['yellow_s','yellow_m','yellow_xl','yellow_xxl','green_s','green_m','green_x','green_xxl']

2 个答案:

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

答案 1 :(得分: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']