2013-02-27 83 views
0

這只是一個思考練習,我會對任何意見感興趣。雖然如果它有效,我可以想到我會使用它的幾種方法。Ruby假設 - 變量嵌套循環

傳統上,如果你想對從陣列或範圍等所形成的嵌套循環的結果的功能,你會寫是這樣的:

def foo(x, y) 
    # Processing with x, y 
end 

iterable_one.each do |x| 
    iterable_two.each do |y| 
     my_func(x, y) 
    end 
end 

但是,如果我不得不添加另一嵌套水平。是的,我可以添加一個額外的循環級別。在這一點上,讓我們讓foo獲取可變數量的參數。

def foo(*inputs) 
    # Processing with variable inputs 
end 

iterable_one.each do |x| 
    iterable_two.each do |y| 
    iterable_three.each do |z| 
     my_func(x, y, x) 
    end 
    end 
end 

現在,假設我需要添加另一個級嵌套。在這一點上,它變得非常粗糙。

因此,我的問題是:是否可以寫下類似的東西?

[iterable_one, iterable_two, iterable_three].nested_each(my_func) 

或也許

[iterable_one, iterable_two, iterable_three].nested_each { |args| my_func(args) } 

也許傳遞參數作爲實際參數是不可行的,你能也許傳遞數組到my_func,並將從可枚舉的組合包含參數?

我很想知道這是否可能,這可能不是一個可能的情景,但在它發生後,我想知道。

回答

3

Array.product產生枚舉的組合,就像它們在嵌套循環中一樣。它需要多個參數。演示:

a = [1,2,3] 
b = %w(a b c) 
c = [true, false] 

all_enums = [a,b,c] 
all_enums.shift.product(*all_enums) do |combi| 
    p combi 
end 


#[1, "a", true] 
#[1, "a", false] 
#[1, "b", true] 
#... 
+0

捂臉。完全忘了產品。 – 2013-02-27 19:30:45

+0

我甚至在前些日子用過它。哦,至少這是我的好奇心滿意。明早需要...... – 2013-02-27 19:43:55

2

您可以使用product

[1,4].product([5,6],[3,5]) #=> [[1, 5, 3], [1, 5, 5], [1, 6, 3], [1, 6, 5], [4, 5, 3], [4, 5, 5], [4, 6, 3], [4, 6, 5]]