IAm*_*NaN 8 ruby ruby-on-rails
如何*args
在Rails中有条件地向数组添加哈希?如果存在原始值,我不想踩踏原始值.
例如,我有一个接收数组的方法:
def foo(*args)
# I want to insert {style: 'bar'} into args but only if !style.present?
bar(*args) # do some other stuff
end
Run Code Online (Sandbox Code Playgroud)
我已经开始使用rails提供的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
Run Code Online (Sandbox Code Playgroud)
它有效,但看起来很冗长,而且不是很红宝石.我觉得我错过了什么.
归档时间: |
|
查看次数: |
1424 次 |
最近记录: |