2014-03-31 92 views
1

我需要多個陣列的每個組合考出來的,就像如下:獲取所有值的每個組合在多個陣列

%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 

,但很明顯,這不是良好的編碼習慣。

這樣做的「紅寶石」方式是什麼?

回答

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

+1,我也是要寫同樣的,但我很高興你發佈了這個方法。 –

+0

愛底部解決方案,非常乾淨可讀,謝謝! – user1029167

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'] } 
+0

我喜歡它,羅伯特!這是一個變體:'(n ** 2).times.map {| i | ('%#{n} b'%n).tr('10','YNN')。split('')}' –