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

时间:2014-03-31 18:58:22

标签: 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"这样做的方式?

2 个答案:

答案 0 :(得分:3)

这应该对你有用

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

答案 1 :(得分:1)

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

[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'] }