Given a class,
class MyClass
def index(arg1, arg2="hello")
end
end
Is it possible to obtain the default value for arg2
, via some methods like Class#instance_method
, or something?
Given a class,
class MyClass
def index(arg1, arg2="hello")
end
end
Is it possible to obtain the default value for arg2
, via some methods like Class#instance_method
, or something?
It seems that only way we can inspect the values of method arguments is by having access to
binding
of method. UsingTracepoint
class, we can get hold of such a binding object and then inspect the values of alloptional
parameters.We need to ensure that we invoke the desired method with only required parameters, so that default parameters gets assigned their default values.
Below is my attempt to do this - it works with both instance methods and class methods. In order to invoke instance methods, we need to instantiate the class - if the constructor requires parameters, then, it can get tricky to create an object. To circumvent that issue, this code dynamically creates a sub-class of given class and defines a no-arg constructor for it.
I think the reason such utility is not made available is that the values of the default arguments are evaluated when they have to be assigned. Therefore, trying to evaluate them might have side additional effects.
Let me tell you a story about the Russian government's nuclear plans:
Here is a poor man's attempt:
Obviously very error prone:
)
or,
in them), but this can be improved.If someone comes up with a purely introspective solution, go with that.