3

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?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

There are other "things" in Ruby that aren't objects either, including operators, blocks, while, for and no doubt others.
More precisely, "foo".upcase send the message upcase to the object "foo". If "foo" implements a method with the same name, it gets invoked.
@Aetherus, if operators were methods, why would we need the term "operator"?
@Aetherus If blocks were methods, why would we need an ampersand to convert it to/from a proc?
@Aetherus: Blocks are not objects - they have no methods, nor can any be sent to them in Ruby's syntax. But they can be wrapped in 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.
|
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.