如何向*args添加哈希?

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)

它有效,但看起来很冗长,而且不是很红宝石.我觉得我错过了什么.

Bor*_*cky 8

是的,#extract_options!是在Rails中实现它的方法.如果你想要更优雅,你必须使用别名,或者找到你自己的方式来处理这个需求,或者由已经完成它的人搜索gem.