Ruby Medium technical 1 views 1 min read

How does self work, and what is the difference between class and instance methods?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Ruby conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?