开发者

Getting/setting an argument's default value dynamically

开发者 https://www.devze.com 2023-01-19 10:03 出处:网络
Start with the following scenario: class Foo def bar(baz={}) p baz end end foo = Foo.new p meth = foo.method(:bar) # => #<Method: Foo#bar>

Start with the following scenario:

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]]

So I can figure out that t开发者_Go百科he method bar is optional, but how do I find the default value ({}) for the method?


Just do this:

foo.bar

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消