8

如何有条件地将哈希添加到*argsRails 中的数组?如果存在的话,我不想踩踏原始价值。

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

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

它可以工作,但看起来很冗长,而且不是很红宝石。我觉得我错过了什么。

4

2 回答 2

8

是的,#extract_options!这是在 Rails 中做到这一点的方法。如果你想更优雅,你必须给它起别名,或者找到你自己的方式来处理这个需求,或者搜索已经做过的人的 gem。

于 2012-06-10T03:07:42.820 回答
0

聚会有点晚了-但如果您需要定期执行此操作,则值得为此使用一些实用方法-例如,如下所示,它将options-hash合并到-ary-args并负责合并它可能存在散列参数或只是将其附加为新散列,如果没有散列存在于args

def merge_into_args!(opts={}, *args)
  opts.each do |key, val|
    if args.any?{|a| a.is_a?(Hash)}
      args.each{|a| a.merge!(key => val) if a.is_a?(Hash)}
    else
      args << {key => val}
    end
  end

  args
end

options如果您想将修改后的-hash 合并回*args并将它们传递给另一个方法,这会派上用场,例如:

 # extract options from args
 options = args.extract_options!

 # modify options
 # ...
 # ...

 # merge modified options back into args and use them as args in another_method
 args = merge_into_args!(options,*args)
 another_method(*args)

 # or as 1-liner directly in the method call:
 another_method(*merge_into_args!(options,*args))

 # and in your case you can conditionally modify the options-hash and merge it 
 # back into the args in one go like this:
 another_method(*merge_into_args!(options.reverse_merge(style: 'bar'),*args))

更多示例:

# args without hash 
args = ["first", "second"]

# merge appends hash
args = merge_into_args!({ foo: "bar", uk: "zok" },*args)
#=> ["first", "second", {:foo=>"bar", :uk=>"zok"}]

# Another merge appends the new options to the already existing hash:   
args = merge_into_args!({ ramba: "zamba", halli: "galli" },*args)
#=> ["first", "second", {:foo=>"bar", :uk=>"zok", :ramba=>"zamba", :halli=>"galli"}]

# Existing options are updated accordingly when the provided hash contains
# identical keys:
args = merge_into_args!({ foo: "baz", uk: "ZOK!", ramba: "ZAMBA" },*args)
#=> ["first", "second", {:foo=>"baz", :uk=>"ZOK!", :ramba=>"ZAMBA", :halli=>"galli"}]
于 2018-06-28T18:18:31.637 回答