2013-04-23 95 views
0

我想在Rails應用程序的方法中添加一個循環。它看起來像這樣如何在一個方法內循環?

Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    child[0]: "child_url" 
) 

有時父母沒有孩子。有時父母會有x個孩子。我如何在一個循環遍歷所有這些孩子的函數中創建一個循環。

我想是這樣

i=0 
children=Child.all 
Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    for child in children 
    child[i]: "child_url" 
    i= i + 1 
    end 
) 

,將產生

Parent.do_something(
     attribute: "a string", 
     parameter: "a string", 
     child[0]: "child_0_url", 
     child[1]: "child_1_url", 
     child[2]: "child_2_url" 
    ) 

如果我沒有解釋的很清楚這個問題,我會更新基於評論我的問題。

+0

你真的需要每個孩子的鑰匙嗎?或者你只是想獲得一個child_urls數組? – 2013-04-23 04:01:50

+0

你究竟想要完成什麼?現在它看起來像你試圖添加一個可變數量的條目到散列然後傳遞給類方法 – AJcodez 2013-04-23 04:05:38

+0

是的,我需要每個條目的一個鍵。我已經更新了這個問題,對不清楚的道歉,我正在努力解決這個問題(甚至是否有可能) – 2013-04-23 04:20:05

回答

1

正如其他人所建議的,它可能是更好的重新設計方法來期望一組孩子,而不是大量的單個參數:

Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    children: ["child_0_url", "child_1_url", "child_2_url"] 
) 

但是,如果你有做到這一點,你說的方式(例如,如果你被別人約束別人的API差):

children = Child.all 
Parent.do_something(
    {attribute: "a string", 
    parameter: "a string"}.merge Hash[*(children.each_with_index.map { |child, i| ["child[#{i}]", child.url] }.flatten)] 
) 

醜陋的,是吧?俗話說得好;如果很難做到,你可能做錯了。 Ismael Abreu的答案的平面地圖非常漂亮。

+0

同意你這很醜陋,絕對不是我喜歡的方法,但這正是我需要的答案。謝謝! – 2013-04-23 14:38:34

1

可能會更容易的部分提取到一個不同的方法:

Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    children: children_method 
) 

def children_method 
    Parent.children.map do |child| 
    # whatever needs to be done 
    end 
end 
2

你可能只是想這樣做:

children = Child.all 
Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    child: children.map { |child| child.url } 
) 
+0

+1假設'child.url'是有效的。希望它給OP提供了足夠的有關如何正確使用map的信息。 – Phrogz 2013-04-23 04:09:28

+0

感謝您的建議。然而,我需要生成可變數量的子對象,即'child [0]:xxxxx,child [1]:yyyyyy,child [2]:.....'這是引起我混淆的部分! – 2013-04-23 04:18:39

+0

這給你的東西就像'child:[xxx,yyy]'。你仍然有相同的數據,但在一個數組中,所以你可以更容易地訪問它。你可能不熟悉'map'方法,它基本上允許你創建一個新的數組,對當前數組的元素進行操作,應用你提供給它的塊。在這種情況下,我調用了一個孩子的url方法(我只是假設有這樣的方法),然後我得到一個相同順序的孩子網址數組。 – 2013-04-23 04:50:41

0

如果你想在喜歡的網址你輸入他們,試試這個:

children = Child.all 
Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    child: something 
) 

def something 
    child = [] 
    children.length.times { |index| child << "child_#{index}_url"} 
    return child 
end 

你也可以更換Child.count children.length如果你不需要在其他地方的孩子,但我假設你做。

編輯:我想這可能是越多,你在找什麼

children = Child.all 
Parent.do_something(
    attribute: "a string", 
    parameter: "a string", 
    child: children.each_with_index.map { |child,i| "child_#{i}_#{child.url}"} 
) 

這需要的,如果沒有塊被賦予each_with_index返回一個枚舉的事實。

1

如果您嘗試將可變數量的參數傳遞給某個方法,那麼您可能正在尋找splat (*) operator

+0

這是一個有用的提示!不完全是我在這裏尋找的東西,但無論如何都很好學習。 – 2013-04-23 14:45:28