Method provides us with an objectification of methods that is helpful in the analysis of these methods before they are called or used. We're constantly playing with our own code, generating, toying with their intermediate object states.
method() returns the
Method object. We call this on
self because we defined
main. Because of this objectification, our code knows more about this method than it would otherwise, as a regular definition. We can store this object and modify it through our code itself, query it and retrieve useful metadata from it.
This looks a lot like the
Proc object that we used in the Blocks chapter of "Ruby Primer: Ascent".
Method objects are, in fact, mostly like
Proc objects however, have a
binding method which returns a
Binding object representing the context in which the
Proc was created. This is because procs have access to the local variables outside their scope. This is untrue of
Method objects because they have a
self binding. This is effectively the same as saying methods can only access variables and objects inside their own scope.
arity method in the above example returns a
Fixnum representing the number of arguments that the method can accept. It returns
-(n + 1), for
n number of required arguments. That is,
-(1 + 1) = -2 as
*args2 is optional. It adds a
+ 1 because
-1 is a reserved number for functions defined using Ruby's C API. If there are no optional arguments then it just returns the correct positive value.
parameter method returns all the parameters that the method is defined with. It returns an array of key-value pairs. The key is a symbol representing the type of the parameter --
:req for a mandatory parameter,
:rest, for the variable arguments,
:opt for the default optional parameters and
:block for the block parameters. The value is the symbolized form of the parameter itself.
In this example,
receiver is the object on which the method is bound and
owner is the class that object belongs to.