我有两个数组,我可以将它们循环加入这两个数组。但是有更好的方法吗?
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"]
我是一名优秀的程序员,十分优秀!