2012-06-10 84 views
7

如何在Rails中有條件地將散列添加到*args數組?如果存在的話,我不想跺跺原來的價值。如何爲* args添加散列?

舉例來說,我有一個接收陣列的方法:

def foo(*args) 
    # I want to insert {style: 'bar'} into args but only if !style.present? 
    bar(*args)        # do some other stuff 
end 

我使用的軌道提供的extract_options和reverse_merge方法開始:

def foo(*args) 
    options = args.extract_options!   # remove the option hashes 
    options.reverse_merge! {style: 'bar'} # modify them 
    args << options       # put them back into the array 
    bar(*args)        # do some other stuff 
end 

它的工作原理,但似乎冗長和不是很紅寶石。我覺得我錯過了一些東西。

+1

是否有原因需要將其放回到'args'列表中?我相信前兩個在Rails源代碼中很常見。 –

+1

好問題。是的,函數'foo'將參數傳遞給另一個函數。我將編輯問題以表明這一點。我在寫一個FormBuilder類,有很多助手調用其他助手。 – IAmNaN

回答

7

是的,#extract_options!是在Rails中完成它的方法。如果你想變得更優雅,你必須給它加上別名,或者找到你自己的方式來處理這種需求,或者由已經完成它的人來尋找寶石。

+1

謝謝,我欣賞反饋。 – IAmNaN