动态获取/设置参数的默认值 [英] Getting/setting an argument's default value dynamically

查看:113
本文介绍了动态获取/设置参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从以下情况开始:

class Foo
  def bar(baz={})
    p baz
  end
end

foo = Foo.new
p meth = foo.method(:bar) # => #<Method: Foo#bar>
p meth.parameters # => [[:opt, :baz]]

因此我可以确定方法bar是可选的,但是如何找到该方法的默认值({})?

So I can figure out that the method bar is optional, but how do I find the default value ({}) for the method?

推荐答案

只需执行以下操作:

foo.bar

由于您没有传递baz的值,它将打印出默认值.

Since you are not passing in a value for baz, it will print out the default value.

尽管如此,我敢打赌你想要一些适用于任何方法的东西.我知道的唯一一致的方法是查看源代码.

Although, I'm betting you want something that would apply to any method. The only consistent way I know of, is to look at the source code.

答案:有人写了一个脚本来完成它此处中获取方法参数和其他信息.

The Answer: Somebody wrote a script that does it here.

但是,查看脚本以尝试了解它如何提取默认值会让我头疼.

However, looking over the script to try and understand just how it pulls out the default values makes my head hurt.

这篇关于动态获取/设置参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆