Chi*_*iya 1 ruby arrays ruby-on-rails ruby-on-rails-3
我有两个数组,我可以加入它们循环这两个数组.但有更好的方法吗?
colors = ['yellow', 'green']
shirts = ['s','m','xl','xxl']
Run Code Online (Sandbox Code Playgroud)
需要输出:
output = ['yellow_s','yellow_m','yellow_xl','yellow_xxl','green_s','green_m','green_x','green_xxl']
Run Code Online (Sandbox Code Playgroud)
使用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"]
Run Code Online (Sandbox Code Playgroud)