Declare them with attr_accessor: attr_accessor :name inside a class writes a name method that returns @name and a name= method that sets it, so person.name = "Ann" works. Use attr_reader for a getter only and attr_writer for a setter only. Inside the class, assign with self.name = value: a bare name = value creates a local variable and never calls the setter.
Ruby objects never expose their instance variables: @name is readable only from the object's own methods, so every outside read or write goes through a method. A getter is a method named after the attribute, a setter is a method whose name ends in =, and obj.name = "Ann" is a call to name=. Coming from Python's @property or JavaScript's get and set: in Ruby a plain attribute and a computed one look the same to the caller, and get_name / set_name names are not idiomatic. The sections below show what attr_accessor generates, when to pick attr_reader or attr_writer instead, the self vs @ question, setters that validate, and Struct and Data as shortcuts, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1attr_accessor and the methods it writesRecommended
attr_accessor is not a keyword. It is a method of Module that runs while the class body is read and defines two instance methods per name you give it: a getter that returns the instance variable and a setter that assigns it. The script below puts a one-line attr_accessor next to the four lines it replaces, and asks each class which methods it has.
# One line: a getter and a setter for @name and @age class Person attr_accessor :name, :age end # What attr_accessor :name writes for you class HandWritten def name @name end def name=(value) @name = value end end person = Person.new p person.name person.name = "Ann" person.age = 31 puts "#{person.name} is #{person.age}" other = HandWritten.new other.name = "Bob" puts other.name p Person.instance_methods(false).sort p HandWritten.instance_methods(false).sort # The instance variable exists once the setter has run p Person.new.instance_variables p person.instance_variables
Output
Both classes report the same kind of methods: [:age, :age=, :name, :name=] for Person and [:name, :name=] for the hand-written one, so the two forms behave the same. The getter returns nil before anything is assigned, because an unset instance variable reads as nil, and a fresh Person has no instance variables at all ([]). attr_accessor declares methods, not fields; set defaults in initialize.
2attr_reader, attr_writer and a private writer
Expose only what callers need. attr_reader gives a getter alone, the right default for values set once in initialize. attr_writer gives a setter alone, for write-only values such as a password or a PIN. When the class itself must change a value but outsiders must not, declare the writer under private (or, since Ruby 3.0, write private attr_writer :balance on one line) and call it as self.balance = … from inside. Calling a method that was never defined raises NoMethodError, and so does calling a private one from outside.
class Account attr_reader :owner, :balance # read-only from outside attr_writer :pin # write-only: no way to read it back def initialize(owner) @owner = owner @balance = 0 end def deposit(amount) self.balance += amount # the private writer, from inside end def pin_ok?(guess) = guess == @pin private attr_writer :balance # only the class itself may set it end account = Account.new("Ann") account.deposit(50) account.deposit(25) puts "#{account.owner}: #{account.balance}" account.pin = "4321" p account.pin_ok?("1234") p account.pin_ok?("4321") begin account.owner = "Eve" rescue NoMethodError => e puts e.message end begin account.balance = 1_000_000 rescue NoMethodError => e puts e.message end begin account.pin rescue NoMethodError => e puts e.message end
Output
deposit raises the balance to 75 through the private writer, but the same writer called from outside fails with private method 'balance=' called for an instance of Account. The read-only owner has no setter at all (undefined method 'owner='), and the PIN can be set and checked but not read back. Note that self.balance += amount expands to self.balance = self.balance + amount, so it uses the getter and the setter together.
3self.name = vs name = vs @name
Inside an instance method, Ruby reads name = value as the creation of a local variable, never as a method call, so it silently skips the setter and the object does not change. Write self.name = value to call the setter. Reading is different: a bare name with no local variable of that name calls the getter, so self. is optional there. Assigning @name directly also works, but it skips any logic the setter has (see the next section), and a misspelled @nmae reads as nil where a misspelled method name raises an error.
class Profile attr_accessor :name def initialize(name) @name = name end # Bug: this creates a local variable called name def rename_broken(new_name) name = new_name end # Fix: self.name = calls the name= method def rename(new_name) self.name = new_name end # Reading needs no self: name calls the getter def greeting "Hi, #{name}" end # A typo in @ reads nil; a typo in a method name raises def typo_ivar = "Hi, #{@nmae}" def typo_method = "Hi, #{nmae}" end profile = Profile.new("Ann") profile.rename_broken("Bob") puts profile.name profile.rename("Bob") puts profile.name puts profile.greeting p profile.typo_ivar begin profile.typo_method rescue NameError => e puts e.message end
Output
After rename_broken("Bob") the name is still Ann: the method assigned a local variable that vanished when it returned, with no warning. rename uses self.name = and the name becomes Bob. The typo lines show why some codebases prefer calling the getter over reading @name: @nmae quietly produces "Hi, ", while nmae fails at once with undefined local variable or method 'nmae' for an instance of Profile. Inside initialize, assigning @name directly is the usual style unless the setter has a check to run.
4Custom setters, computed getters and predicates
When a value needs checking, keep attr_reader and write the setter yourself: a method named celsius= that raises ArgumentError on bad input and assigns the instance variable otherwise. Call it from initialize with self.celsius = so new objects get the same check. A getter does not have to read a stored value: it can compute one, and a matching setter can convert back. Methods that answer yes or no end in ? by convention, as in def admin? = @admin. The one-line def … = expr form (Ruby 3.0+) suits getters; a setter cannot be written that way and needs a normal def.
class Temperature attr_reader :celsius def initialize(celsius) self.celsius = celsius # run the check on creation too end # A setter that validates before it stores def celsius=(value) unless value.is_a?(Numeric) && value >= -273.15 raise ArgumentError, "invalid temperature: #{value.inspect}" end @celsius = value end # A computed getter and setter: no @fahrenheit is stored def fahrenheit = celsius * 9.0 / 5 + 32 def fahrenheit=(value) self.celsius = (value - 32) * 5.0 / 9 end # A predicate getter ends in ? def freezing? = celsius <= 0 end t = Temperature.new(25) p t.fahrenheit t.fahrenheit = 212 p t.celsius p t.freezing? t.celsius = -5 p t.freezing? begin t.celsius = -300 rescue ArgumentError => e puts "#{e.class}: #{e.message}" end p t.celsius begin Temperature.new("hot") rescue ArgumentError => e puts "#{e.class}: #{e.message}" end # A boolean flag: attr_writer plus a ? reader class Member attr_writer :admin def admin? = @admin == true end m = Member.new p m.admin? m.admin = true p m.admin?
Output
A temperature of 25 reads as 77.0 through the computed getter, and setting fahrenheit = 212 stores 100.0 in @celsius. The rejected -300 raises ArgumentError: invalid temperature: -300 and leaves the old value -5 in place, and Temperature.new("hot") fails the same check because initialize goes through the setter. The Member flag starts as false rather than nil because admin? compares with true. attr_accessor :admin? is not an option: Ruby rejects it with invalid attribute name 'admin?'.
5Shortcuts: Struct and Data
For a class that is mostly fields, Struct.new(:x, :y) builds one with a getter and a setter per field, a constructor, == by value and a readable inspect. Data.define (Ruby 3.2+) does the same for immutable values: getters only, every field required, and with to make a changed copy. Both take a block for your own methods. Since Ruby 3.2 a Struct accepts keyword arguments without keyword_init: true; on older versions pass that option to get them.
# Struct: a class with a getter and a setter per field Point = Struct.new(:x, :y) pt = Point.new(1, 2) pt.x = 10 p pt.x p pt p pt == Point.new(10, 2) # Keyword arguments work too (Ruby 3.2+, or keyword_init: true) User = Struct.new(:name, :email) p User.new(name: "Ann") # Data (Ruby 3.2+): getters only, keyword or positional args Coord = Data.define(:lat, :lng) do def to_s = "(#{lat}, #{lng})" end home = Coord.new(lat: 51.5, lng: -0.1) p home puts home p home.lat begin home.lat = 0 rescue NoMethodError => e puts e.message end # "Change" a Data value by making a copy paris = home.with(lat: 48.9, lng: 2.35) puts paris puts home begin Coord.new(lat: 1) rescue ArgumentError => e puts e.message end
Output
The struct prints as #<struct Point x=10, y=2> and compares equal to a new point with the same values. A field you leave out of a Struct is nil (email=nil), while Data refuses with missing keyword: :lng. The Data object has no lat=, and with returns a new value, so home still prints (51.5, -0.1) after paris is made. Reach for a full class with attr_* when the object has behavior and checks; use these when it is mostly data.
6Which should you use?
| Method | Generates | Best for |
|---|---|---|
| attr_reader :x | Getter | The default: values set in initialize |
| attr_accessor :x | Getter + setter | Fields callers may change freely |
| attr_writer :x | Setter | Write-only values, or private writers |
| def x=(v) … end | Your setter | Validation or conversion on assignment |
| def admin? = @admin | Predicate getter | Yes or no questions about the object |
| Struct.new(:x, :y) | Class + accessors | Mutable records with little behavior |
| Data.define(:x, :y) | Class + getters | Immutable values (Ruby 3.2+) |
Frequently asked questions
What is attr_accessor in Ruby?
A class-level method that defines a getter and a setter for each name you pass. attr_accessor :name is the same as writing def name; @name; end and def name=(value); @name = value; end. It does not create the instance variable; @name reads as nil until something assigns it.
Why does name = value inside a method not call my setter?
Ruby treats name = value as the assignment of a local variable, so the setter never runs and the object keeps its old value. Write self.name = value. Reading has no such problem: a bare name calls the getter when there is no local variable with that name.
Should I use @name or self.name inside the class?
Use self.name = value when the setter does something (validation, conversion) or when the writer is the only public contract. Assigning @name directly is common in initialize and in simple classes. For reading, the getter name raises on a typo while a misspelled @nmae silently reads as nil.
How do I read an instance variable that has no getter?
From outside, obj.instance_variable_get(:@secret) returns its value (or nil if it was never set), and instance_variable_set(:@secret, 7) changes it; instance_variables lists them. These skip encapsulation, so keep them for debugging, serialization and metaprogramming, not for everyday access.
What does a setter return?
An assignment like obj.m = 3 always evaluates to the right-hand side, 3, whatever the m= method returns. Only calling it as a method, obj.send(:m=, 3), gives you its real return value. So a setter cannot hand back a cleaned-up value through the assignment.
How do I add a getter and setter on the class itself?
Open the singleton class: class << self; attr_accessor :level; end inside the class body. Then Config.level = 3 and Config.level work on the class, with the value stored in an instance variable of the class object.