Getting/setting an argument's default value dy

2019-08-27 20:04发布

问题:

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 the method bar is optional, but how do I find the default value ({}) for the method?

回答1:

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.