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

Ruby 获取多个数组中所有值的每个组合,ruby,loops,enums,iterator,Ruby,Loops,Enums,Iterator,我需要测试多个阵列的每个组合,如下所示: %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是如何做到这一

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

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

这应该对你有用

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

由于您只有两个选项,因此可以使用二进制扩展:

[0..2**3-1].each do |indicator|
  first_indicator, second_indicator, third_indicator =
    (0..2).map { |i| { '0' => 'N', '1' => 'Y'}[indicator.to_s(2)[i] || '0'] }

由于您只有两个选项,因此可以使用二进制扩展:

[0..2**3-1].each do |indicator|
  first_indicator, second_indicator, third_indicator =
    (0..2).map { |i| { '0' => 'N', '1' => 'Y'}[indicator.to_s(2)[i] || '0'] }

+我也准备写同样的东西,但是我很高兴你发布了这个方法。喜欢底部的解决方案,非常干净易读,谢谢+我也准备写同样的东西,但是我很高兴你发布了这个方法。喜欢底部的解决方案,非常干净易读,谢谢!我喜欢,罗伯特!这里有一个变体:n**2.times.map{i|i{n}%b%n.tr'10','YNN'.split}我喜欢它,罗伯特!这里有一个变体:n**2.times.map{i|i{n}b%n.tr'10','YNN'.split}