我需要测试多个数组的每个组合,如下所示:
%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"]]
或者因为你只有两个选择重复三次这更干净
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/