Is method an object in Ruby? My friend asked me this question.I read about this in website.But still I didn't understand it.Can anyone help me?
2 Answers
There seems to be a confusion here due to ambiguity of the term method. Method in the most ordinary sense is not an object. In the following:
"foo".upcase the method upcase is applied to an object "foo", but upcase is not an object, as can be seen by the fact that it cannot stand alone:
upcase # => error (Do not confuse this with when it can be considered that the receiver is omitted).
However, there is a class Method, whose instances correspond to methods, and are objects. They may also be called methods, but that is not the normal usage of the term method.
7 Comments
while, for and no doubt others."foo".upcase send the message upcase to the object "foo". If "foo" implements a method with the same name, it gets invoked.Proc objects. Passing blocks into methods is much, much faster than constructing Proc objects and passing them as regular parameters; this is largely because blocks do not need to deal with the OO overhead. Similarly, methods are not objects, but can be wrapped in Method and UnboundMethod objects.No, they are not.
Methods themselves are a language structure of Ruby, and they are not objects. But there is a class Method, whose instances represent methods, and can be called using Method#call.
Also, there is another kind of instances - instances of class UnboundMethod, which represent methods that are detached from specific objects. They can't be called directly, but can be used in many different ways.
If you are looking for something like Javascript's functions, then procs and lambdas are what you want.