gpt4 book ai didi

ruby-on-rails - 将一个数组的每个元素连接到 ruby​​ 中另一个数组的每个元素

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:30 25 4
gpt4 key购买 nike

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

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"]

关于ruby-on-rails - 将一个数组的每个元素连接到 ruby​​ 中另一个数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26299464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com