How does self work, and what is the difference between class and instance methods?
Assesses fundamental understanding of Ruby conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
self is the current object. Inside an instance method it is the receiver, inside a class body it is the class, and inside a class method it is the class as well.
class Widget
def initialize(name)
@name = name
end
def self.default
new("default") # class method
end
class << self
def count
@count ||= 0 # class-level instance variable
end
end
end
Widget.default
Defining def self.foo adds a singleton method to the class object, so it is called on the class rather than an instance. Instance variables differ by context: @name in an instance method belongs to the instance, while @count in a class method belongs to the class object.
self is also required to call an attribute writer, as in self.name = value, because a bare name = value would create a local variable instead.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.