Skip to content
Poignant Guide Ruby Q&A

What does self mean inside a Ruby class?

Asked by Ngozi A. · Classes, modules and objects2 repliesupdated

Short answer

I am building my first Rails app for a client and I keep meeting self in models: def self.recent, self.status = "paid", and sometimes plain status = "paid". I can copy these, but I do not understand them, and last week one of them silently did nothing.

Written by Ngozi A. ·
CitePoignant Guide Ruby Q&A, "What does self mean inside a Ruby class?", https://poignantguide.net/answers/read/what-does-self-mean-inside-a-ruby-class/, accessed 2026-12-01.
  1. Member ·

    Here is a small version of the bug, outside Rails:

    class Invoice
      attr_accessor :amount
    
      def self.build(amount)
        new(amount)
      end
    
      def initialize(amount)
        @amount = amount
      end
    
      def apply_discount
        amount = @amount * 0.9
      end
    end
    
    invoice = Invoice.build(100)
    invoice.apply_discount   # => 90.0
    invoice.amount           # => 100
    

    The method returns 90.0 but the invoice keeps its old amount. No error, no warning. I am on Ruby 3.3 and I ran this in irb.

    So what is self exactly? Is it the same thing in def self.build and inside apply_discount? And why does amount = ... not change the object when I have an attr_accessor? I want the mental model, not only the fix.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. Wes O.Member ·

    The old-timer comparison: this in C++ or Java. Except Ruby changes what it means at the class level as well. puts self right inside class Invoice prints Invoice, because the class body is also code that is running, and the thing running it is the class.

  2. Anouk L.Member ·

    I explain it to my club (14 and 15 year olds) as "self means me, the object whose method is running right now". Inside apply_discount, "me" is the invoice. Inside def self.build, "me" is the class Invoice itself, so self.build is a method that belongs to the class.

Poignant Guide Ruby Q&A. Questions and answers on learning Ruby and programming: syntax, blocks, objects, gems, Rails, debugging and reading the Poignant Guide.