“Self” in Ruby
What is “self”?
“Self” is the current object. The object to which a method is applied or the object which receives the method call is “self”. The current object depends on the context.
To know which object is “self”, we need to know what context the program is in at given time. As a program runs, its context constantly changes. Context is where your code is now as the program runs.
Self at the top level of the program(outside any class or module)
So, what is “self” when program execution is at top of the program and is outside of any class or module definition block?
As you can see in the above code the output for self is “main” . In Ruby, the object at the top level is called “main” and is an instance of Object class. So “main” is the top-level context of the Ruby program.
And the same applies to a method that is defined at the top level of the program:
Methods defined at the top level are bound to the “main” object.(Note: You will notice “nil” being returned at the end in the above code, that is because “puts” always returns “nil”).
Self inside class or module definitions
“Self inside a class refers to the class object.
Similarly, “self” inside a module refers to the module object.
Self inside an instance method definition
But when we define a method inside a class, “self” is the object that gets created(Library.new) ie., an instance of the class.
The output #<Library:0x0000557821504418> indicates that it is an instance of class Library. In the above code the variable “library” is the receiver of the message “books” (Note: Calling methods or sending messages to objects involves dot notations --> library.books).
Self inside a class method
Since it is a class method, “self” refers to the class.
Self inside a Singleton method
Methods you define for a single object are called singleton methods. “Self” here is the object that owns the method.
Summary
So “self” in Ruby is a reserved keyword that refers to the default object. The value of “self” depends on the execution context.
Thanks for reading.










