What does self mean inside a Ruby class?
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.
Cite
Poignant 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.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 # => 100The 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
selfexactly? Is it the same thing indef self.buildand insideapply_discount? And why doesamount = ...not change the object when I have anattr_accessor? I want the mental model, not only the fix.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.