gpt4 book ai didi

ruby - 获取多个数组中所有值的每个组合

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

我需要测试多个数组的每个组合,如下所示:

%w[Y N].each do |first_indicator|
%w[Y N].each do |second_indicator|
%w[Y N].each do |third_indicator|
#do stuff with first_indicator, second_indicator, third_indicator
end
end
end

但很明显这不是好的编码习惯。

执行此操作的“Ruby”方法是什么?

最佳答案

这对你有用

a =[['Y','N'],['Y','N'],['Y','N']]
#=> [["Y", "N"], ["Y", "N"], ["Y", "N"]]
a.flatten.combination(a.size).to_a.uniq
#=> [["Y", "N", "Y"], ["Y", "N", "N"], ["Y", "Y", "N"], ["Y", "Y", "Y"], ["N", "Y", "N"],["N", "Y", "Y"], ["N", "N", "Y"], ["N", "N", "N"]]

或者因为你只有 2 个选项重复 3 次,所以这更干净

a = ["Y","N"]
a.repeated_permutation(3).to_a
#=> [["Y", "Y", "Y"], ["Y", "Y", "N"], ["Y", "N", "Y"], ["Y", "N", "N"], ["N", "Y", "Y"], ["N", "Y", "N"], ["N", "N", "Y"], ["N", "N", "N"]]

关于ruby - 获取多个数组中所有值的每个组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22769917/

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