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
它的工作原理,但似乎冗長和不是很紅寶石。我覺得我錯過了一些東西。
是否有原因需要將其放回到'args'列表中?我相信前兩個在Rails源代碼中很常見。 –
好問題。是的,函數'foo'將參數傳遞給另一個函數。我將編輯問題以表明這一點。我在寫一個FormBuilder類,有很多助手調用其他助手。 – IAmNaN