简体   繁体   English

是否可以在 Ruby 中获取关键字 arguments 的默认值?

[英]Is it possible to get the default value for keyword arguments in Ruby?

I am looking to get the default values for a function with keyword arguments.我正在寻找带有关键字 arguments 的 function 的默认值。 Example:例子:

def some_method(foo: 1, bar: 2)
end

My expected output would be something like我预期的 output 会像

{ foo: 1, bar: 2 }

Theparameters method defined on method only provides parameter names.方法上定义的参数方法只提供参数名称。

You can get the keys, but not the values, because they aren't actually set until the method is actually invoked.您可以获取键,但不能获取值,因为在实际调用方法之前它们不会被实际设置。 You can get the method's parameters usingMethod#parameters .您可以使用Method#parameters获取方法的参数。 For example, using your example code from above:例如,使用上面的示例代码:

method(:some_method).parameters
#=> [[:key, :foo], [:key, :bar]]

However, the:foo and:bar keys aren't actually set until the method is run, so there's no way to get the "value" except possibly to introspect the method definition itself.但是,在方法运行之前,实际上并没有设置 the:foo 和:bar 键,因此除了可能内省方法定义本身之外,没有办法获取“值”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM