加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何向* args添加哈希?

发布时间:2020-12-16 19:12:50 所属栏目:百科 来源:网络整理
导读:如何有条件地在Rails中向* args数组添加哈希?如果存在原始值,我不想踩踏原始值. 例如,我有一个接收数组的方法: def foo(*args) # I want to insert {style: 'bar'} into args but only if !style.present? bar(*args) # do some other stuff end 我已经开
如何有条件地在Rails中向* args数组添加哈希?如果存在原始值,我不想踩踏原始值.

例如,我有一个接收数组的方法:

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

我已经开始使用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

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读