我有两个数组,我可以通过这两个数组来连接它们但有没有更好的方法呢?
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']
最佳答案
使用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"]