What is the difference between self in different contexts (Instance vs Class vs Module)?
Updated May 17, 2026
Short answer
self always refers to the current execution context object: the specific instance inside instance methods, and the Class/Module object itself inside class/module scopes.
Deep explanation
In Ruby, everything is executed within the context of a current object, tracked via self. At the top level, self is the root object main. Inside a class definition block but outside any methods, self is the class object itself. Inside an instance method, self refers to the specific instance of the class that invoked the method. Inside a class method, self refers to the class object.
Real-world example
Using self inside an instance method to pass the current state out to an external service (Notification.send(user: self)), or using def self.method_name to define clear class utility paths.
Common mistakes
- Explicitly prepending `self.` to call private or protected readers inside an instance method, causing a `NoMethodError` prior to Ruby 2.7 (which now permits `self.private_method`).
Follow-up questions
- What is the singleton class of an object?
- How do you access the singleton class explicitly?