How do attr_accessor, attr_reader and attr_writer work in Ruby?
They write small methods for you. attr_reader creates a method that returns an instance variable, attr_writer creates a method that sets it, and attr_accessor creates both. Ruby hides instance variables from the outside by default, so these three are how other code is allowed to read or change an object's state.
Cite
Poignant Guide Ruby Q&A, "How do attr_accessor, attr_reader and attr_writer work in Ruby?", https://poignantguide.net/answers/read/how-do-attr-accessor-attr-reader-and-attr-writer-work-in-ruby/, accessed 2026-11-19.- Odile MarchettiStaffStaff: Ruby basics, objects and the Poignant Guide ·
The short version, runnable
An instance variable is a variable that starts with
@and belongs to one object. Paste this into irb:class Dog attr_accessor :name # read and write attr_reader :id # read only attr_writer :mood # write only def initialize(name) @name = name @id = 7 end end d = Dog.new("Rex") p d.name # => "Rex" d.name = "Max" p d.name # => "Max" p d.id # => 7 d.id = 9 # NoMethodError: undefined method `id=' for an instance of DogWithout the
attr_lines you could not even writed.name. Ruby objects keep their instance variables private, and the only way in is a method. That is the whole reason these helpers exist.What Ruby writes for you
The Module documentation says attr_accessor "creates an instance variable (
@name) and a corresponding access method to read it" and "also creates a method calledname=to set the attribute". So these two classes behave the same:class Short attr_accessor :name end class Long def name @name end def name=(value) @name = value end endA method ending in
=is a setter, and Ruby lets you call it with spaces around the equals sign, sod.name = "Max"really meansd.name=("Max"). You can see what was generated:p Dog.instance_methods(false).sort # => [:id, :mood=, :name, :name=]Each helper returns an array of the method names it defined, and takes symbols (
:name) or strings. If symbols are new to you, this thread on symbols explains why the colon is there.Which one do I pick?
You write Reading obj.xWriting obj.x = 1Use it when attr_reader :xyes no the value is set once, in initializeattr_writer :xno yes other code gives it a value but never asks for it back attr_accessor :xyes yes callers may read and change it Start with
attr_reader. Promote toattr_accessoronly when something outside the class needs to change the value. A smaller door is easier to keep tidy. On this site's copy of Why's (Poignant) Guide to Ruby, the classes chapter showsattr_accessoron a Fox class and notes thatattr_readerandattr_writergive you half each.Mistakes beginners make
Forgetting self when assigning inside the class. This is the classic one. Inside a method,
lives = 5creates a brand new local variable, it does not call the setter:class Cat attr_accessor :lives def initialize @lives = 9 end def lose_life lives = @lives - 1 # local variable, the cat is unchanged end def lose_life_properly self.lives = lives - 1 # calls lives= end end c = Cat.new c.lose_life p c.lives # => 9 c.lose_life_properly p c.lives # => 8Writing
@lives -= 1also works, and skips the setter altogether. Reading withlivesneeds noself; only assignment does.Expecting attr_writer to give you a reader. Call
d.moodon the Dog above and Ruby raises a NoMethodError saying there is no method named mood (it may even suggestmood=as the near miss). If you need both, useattr_accessor.Using attr_accessor for everything. It lets any code overwrite the value with anything, including
nil. When a value needs checking, write the setter yourself and keep the reader from the helper:class Temp attr_reader :degrees def initialize(degrees) @degrees = degrees end def degrees=(value) raise ArgumentError, "too cold" if value < -273 @degrees = value end endMaking a private attribute public by accident. Helpers called after
privatebecome private methods. Private methods can only be called without a receiver, apart fromself.name = ..., as the syntax documentation on classes and modules describes. That is a useful trick when only the class itself should touch a value.Check this in order
- Is the error
undefined methodending in=? You are missing a writer. Addattr_writerorattr_accessor. - Is it
undefined methodwithout the=? You are missing a reader. - Does an assignment inside a method seem to do nothing? Add
self.in front of the name. - Does the attribute come back
nil? Check thatinitializeactually assigns@name, and check the spelling of the instance variable. - Still stuck? Print
d.instance_variablesto see what the object really holds. In the Dog above it gives[:@name, :@id, :@mood]once the mood has been set.
Checked on 12 November 2026.
- Is the error
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.