The main Object
In this chapter, you will learn about the main object and that the instance variables at the top level is bound to the main object.
In Ruby, everything in executed in the context of some object. The methods are bound to the value of self. Whenever self points to main, the methods are bound to main.
What is a main Object?
The main is the object at the top level. It is an instance of Object. Any methods defined in main become instance methods of Object. This makes them available everywhere, meaning that we can call the method without a receiver.
Memory Location of main Object
Let's look at an example.
This will print the object_id. On my computer, it is:
The object_id will change every time you run the program. Because, it represents the integer identifier for the main object. Ruby creates a new main object every time you run the program.
The above code is same as:
Memory Location of Instance Variable
Let's print the instance variable at the top level.
@age = 22 puts @age
The age will be the same every time you run the program. The object_id of the number 22 will be the same. We can verify this:
@age = 22 puts @age.object_id
This always prints 45 on my laptop. The reason is that Ruby reuses some objects of built-in classes for optimization.
Instance Variables at the Top Level
Instance variables defined in the top level context are also bound to the main object. Let's look at an example.
@age = 22 p self.instance_variables
We know that the value of self is main at the top level. The output shows that age instance variable is bound to the main object.
Methods at the Top Level
Let's define a method at the top level.
def learn p 'learning' end learn
Let's trace the value of main as the program executes.
p self def learn p self p 'learning' end p self learn
main main main learning
The value of self is main throughout the program.
Can we use self to call this method?
def learn p 'learning' end self.learn
This results in an error.
NoMethodError: private method ‘learn’ called for main:Object
The methods defined at the top level becomes private method in the Object. This shows that these methods are bound to the main object.
Why does Ruby add the top level methods as the private methods to the main object?
The reason is that if it adds it as a public method, sub classes will inherit those methods. This will pollute the sub classes with unnecessary methods in the public interface.
In this chapter, you learned about the main object. You learned how the instance variables and methods defined at the top level is bound to the main object.