我有几个方法接受许多(关键字)参数,这些参数最终将同一组参数传递给另一个方法。
下面是正常的
def foo(a:, b:, c:, d:, e:)
bar('var', a:a, b:b, c:c, d:d, e:e)
end
# takes the same arguments as #foo + one more
def bar(var, a:, b:, c:, d:, e:)
...
end
这有点乏味和烦人。我想知道 Ruby 核心中是否有任何东西可以轻松地执行以下操作...
def foo(a:, b:, c:, d:, e:)
bar('var', <something that automagically collects all of the keyword args>)
end
我知道您可以解析 method(__method__).parameters
,做一些体操,然后将所有内容打包成一个散列,该散列可以双拼并传递给 bar
。我只是想知道核心中是否已经有一些东西可以以一种漂亮、整洁的方式做到这一点?
如果有一些东西可以更普遍地应用,即不仅适用于关键字参数,那当然也很有趣。
最佳答案
是的,**args
will gather arbitrary keyword arguments作为哈希。再次使用 ** 将散列扁平化为 bar
的关键字参数,Ruby 3 将不再为您执行此操作。
def foo(**bar_args)
# The ** is necessary in Ruby 3.
bar('var', **bar_args)
end
def bar(var, a:, b:, c:, d:, e:)
puts "#{var} #{a} #{b} #{c} #{d} #{e}"
end
如果 foo
从不使用这些参数,这是合适的,它只是将它们传递给 bar
。如果 foo
要使用一些参数,则应在 foo
中定义这些参数。
def foo(a:, **bar_args)
puts "#{a} is for a"
bar('var', a: a, **bar_args)
end
def bar(var, a:, b:, c:, d:, e:)
puts "#{var} #{a} #{b} #{c} #{d} #{e}"
end
关于ruby - 在 Ruby 中有 "repackage"关键字参数的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66589064/