Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods in Ruby: objects or not?

Inspired by this discussion, after some googling I wasn't able to find an answer to a pretty simple question regarding methods in Ruby: are methods objects or not?

There are different opinions here and there, and I would really like to hear, let's say, an in-depth explanation.

I'm aware of Object#method method, which takes a method name and returns a Method instance, but, on the other hand, there's a similar thing you can do with blocks to make them into Proc instances, and blocks aren't objects, so what makes methods any different?

like image 855
Mladen Jablanović Avatar asked Apr 08 '10 18:04

Mladen Jablanović


People also ask

Does Ruby have methods?

Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name.

What is not an object in Ruby?

The short answer is No. Blocks are not objects in Ruby. We need to use Proc, lambda or literal constructor ->, to convert blocks into objects. In Smalltalk, blocks are objects.

What are Ruby objects?

Everything in Ruby is an object. All objects have an identity; they can also hold state and manifest behaviour by responding to messages. These messages are normally dispatched through method calls. A string is an example of a Ruby object.

Is everything an object in Ruby?

Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.


1 Answers

Methods are a fundamental part of Ruby's syntax, but they are not values that Ruby programs can operate on. That is, Ruby's methods are not objects in the way that strings, numbers, and arrays are. It is possible, however, to obtain a Method object that represents a given method, and we can invoke methods indirectly through Method objects.

From The Ruby Programming Language:
alt text

like image 80
JRL Avatar answered Sep 18 '22 14:09

JRL