聚会有点晚了-但如果您需要定期执行此操作,则值得为此使用一些实用方法-例如,如下所示,它将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"}]