Thuta Learning
Ruby
AdvancedProgrammingBeginner

Getters & Setters

RubyLesson 1930 min

What you'll walk away with

  • Say which methods attr_reader, attr_writer and attr_accessor each define
  • Write a custom setter with def age=(value) that validates or normalises its input
  • Tell self.age = value (calls the setter) apart from age = value (makes a local variable)
  • Use private and protected correctly, including their effect on attr_* lines below them
  • Stop a reader from leaking a mutable array that callers can change from outside

Explain it simply

Getters and setters in plain language

Picture an object as a small shop with a front desk. The shelves behind the desk are its instance variables, such as @name and @balance, and nobody outside can walk in and touch them. Customers can only ask the clerk, which in Ruby means calling a method. A getter is the method that reads a value for you, and a setter is the method that accepts a new value and puts it on the shelf.

Ruby gives you attr_reader, attr_writer and attr_accessor to generate the boring getters and setters in one line. When a value needs rules, for example an age that cannot be negative, you write the setter yourself and make it refuse bad data at the front desk. That is the whole idea: every change goes through one method that can check it.

Problem → Why → Solution

The problem: attr_accessor lets anything in

A beginner's first class usually gets attr_accessor for every field, because it is the quickest way to make the code work. The trouble is that the attr_accessor writer stores the new value without asking any question. The Person below happily accepts a negative age and even the string "thirty", and nothing complains until a completely different line tries to calculate with it.

Because the bad value was stored silently, the error shows up far from the cause. The stack trace points at person.age + 1, but the line that actually broke the object is the assignment, which may be in another file or a loop earlier. Debugging that gap is the real cost.

person_problem.rb
class Person
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end
end

person = Person.new("Aye", 30)
person.age = -4          # accepted: nobody checks
person.age = "thirty"    # accepted too
puts person.age + 1      # TypeError: no implicit conversion of Integer into String

Why a custom setter fixes it

An attr_accessor setter is only a one-line assignment, so it cannot refuse anything. A setter you write yourself is an ordinary method, which means it can validate, clean up or convert the value before it touches the instance variable. With the check in one place, every route into the object, including initialize, gets the same protection.

Core concept: readers, writers and the front desk

Instance variables belong to the object alone. Calling person.age from outside raises NoMethodError unless a method called age exists. The shortest way to create it is attr_reader :age, which is equivalent to def age; @age; end. attr_writer :age defines def age=(value); @age = value; end, and attr_accessor :age defines both. These macros run once, while the class body is being read.

attr_macros.rb
class Pet
  attr_reader :name            # same as: def name = @name
  attr_writer :mood            # same as: def mood=(value); @mood = value; end
  attr_accessor :age           # reader and writer in one line

  def initialize(name)
    @name = name
  end
end

pet = Pet.new("Mimi")
pet.age = 3
pet.mood = :happy
p pet.name, pet.age                      # "Mimi" then 3
p pet.respond_to?(:mood)                 # false: attr_writer has no reader
p pet.respond_to?(:mood=)                # true
p Pet.instance_methods(false).sort       # [:age, :age=, :mood=, :name]

A setter is a normal method whose name happens to end in an equals sign. The assignment person.age = 31 is just a nicer way to write person.age=(31). Because it is an ordinary method, you can replace the generated one with your own and put rules inside: raise an ArgumentError for bad data, strip whitespace, convert a string to an integer. Ruby also decides what the assignment expression returns: it is always the right-hand side, so result = (person.age = 40) gives 40 whatever your setter returns.

Inside the class, call your own setter with an explicit self. Writing age = value creates a brand-new local variable that disappears when the method ends, and the object is not touched at all. Writing self.age = value calls age=. Use the same rule in initialize, so the validation also protects objects at the moment they are created. Setting @age = value directly skips the setter, which is right only for trusted internal code.

Visibility controls who may call a method. Public methods, the default, can be called by anyone. Private methods can only be called from inside the object, without an explicit receiver (self. is also allowed). Protected methods can be called with an explicit receiver, but only from code running inside an instance of the same class or a subclass, which is exactly what comparisons between two objects need. The word private on a line of its own affects every method defined below it, and that includes attr_reader, attr_writer and attr_accessor lines.

LevelWho can call itTypical use
publicAnyone, with an explicit receiverThe object's outward interface
protectedCode inside an instance of the same class, with a receiverComparison helpers such as other.balance
privateOnly the object itself, no receiver (self. is allowed)Internal helpers and setters you do not expose
Mental model: the front desk
  1. Caller writes obj.age = 31
  2. Ruby calls the age= method
  3. Setter validates, then sets @age
  4. The expression evaluates to 31

A setter is just a method named with a trailing =, so any rule you can write in Ruby can guard the assignment.

General pattern

ruby
class ClassName
  attr_reader :read_only         # getter only
  attr_writer :write_only        # setter only
  attr_accessor :both            # getter and setter

  def value=(new_value)          # hand-written setter
    raise ArgumentError, "reason" unless valid?(new_value)
    @value = new_value
  end
  private attr_reader :internal  # private getter
end

The attr_* lines generate methods, and def value=(new_value) is a hand-written setter that checks first and only then sets @value. private attr_reader :internal makes the reader private in a single line.

Example: a BankAccount that validates its owner and protects its balance

BankAccount below combines every idea from this lesson. owner has a hand-written setter that cleans and validates the text, balance can be read by anyone but changed only through deposit, and the private attr_writer makes direct assignment impossible from outside.

The error text in the output is what Ruby 4.0.9 prints. Ruby 3.4 and later quote method names with plain apostrophes, as in 'balance=', while older versions print a backtick and an apostrophe, so the exact wording can differ on an older install.

bank_account.rb
class BankAccount
  attr_reader :owner, :balance

  def initialize(owner, balance = 0)
    self.owner = owner
    @balance = balance
  end

  def owner=(value)
    name = value.to_s.strip
    raise ArgumentError, "owner can't be blank" if name.empty?

    @owner = name
  end

  def deposit(amount)
    raise ArgumentError, "deposit must be positive" unless amount.positive?

    self.balance += amount
    self
  end

  def richer_than?(other)
    balance > other.balance
  end

  private

  attr_writer :balance
end

account = BankAccount.new("  Aye  ", 100)
puts account.owner
account.deposit(50)
puts account.balance

begin
  account.balance = 1_000_000
rescue NoMethodError => e
  puts "blocked: #{e.message}"
end

begin
  account.owner = "   "
rescue ArgumentError => e
  puts "rejected: #{e.message}"
end
puts account.owner
puts account.richer_than?(BankAccount.new("Ko", 10))

Code breakdown

  1. Public readersattr_reader :owner, :balance

    Anyone can read owner and balance. The line sits above private, so both readers are public. The writer for balance is declared separately below, as private.

  2. initializeself.owner = owner

    The self. makes this call the validating setter owner=. Writing owner = owner would only assign the parameter to itself and never touch the object.

  3. The gateraise ArgumentError, "owner can't be blank" if name.empty?

    After stripping, a blank name raises ArgumentError. @owner is never touched until this line is passed, so the object always stays in a valid state.

  4. Private writer used with self.self.balance += amount

    This expands to self.balance = self.balance + amount. Calling the private writer with self. from inside the class is allowed. Without self., balance += amount creates a local variable balance that starts out as nil, and the line fails with NoMethodError, "undefined method '+' for nil".

  5. Private attr_writerattr_writer :balance

    It sits below the private keyword, so balance= is private. Writing account.balance = ... from outside raises NoMethodError.

  6. Reading the errorputs "blocked: #{e.message}"

    The NoMethodError message, private method 'balance=' called for an instance of BankAccount, says exactly why the call was refused. Learning to read messages like this makes debugging faster.

You should see
Aye
150
blocked: private method 'balance=' called for an instance of BankAccount
rejected: owner can't be blank
Aye
true

Custom setters: validate, normalise, convert

A setter can do three kinds of work. It can reject bad data with an exception, it can normalise good data (strip whitespace, lower-case an email) and it can convert between types. The Person class below does the first two: name= strips and refuses blank text, age= accepts only whole numbers from 0 to 150. Notice the last two lines of the code: the value of an assignment expression is the right-hand side, never the return value of the setter, so you cannot signal a failure by returning false. Raise an exception instead.

person_setters.rb
class Person
  attr_reader :name, :age

  def initialize(name, age)
    self.name = name
    self.age = age
  end

  def name=(value)
    clean = value.to_s.strip
    raise ArgumentError, "name can't be blank" if clean.empty?

    @name = clean
  end

  def age=(value)
    unless value.is_a?(Integer) && value.between?(0, 150)
      raise ArgumentError, "age must be 0..150, got #{value.inspect}"
    end

    @age = value
  end
end

person = Person.new("  Aye  ", 30)
p person.name                  # "Aye"

person.age = 31
p person.age                   # 31

[-4, "old", 2.5].each do |bad|
  person.age = bad
rescue ArgumentError => e
  puts "rejected: #{e.message}"
end
p person.age                   # still 31

result = (person.age = 40)
p result                       # 40, the right-hand side

private, protected and where the attr_* lines go

private, protected and public are methods. Called with no arguments they switch the default visibility for every def that follows in the class body. They also apply to attr_reader, attr_writer and attr_accessor lines below them, because those macros define methods like any other. You can be specific too: private :helper makes one existing method private, and private attr_reader :pin does it in one line, because the attr_* macros return the names of the methods they define. The Account class below has one protected reader and one private reader.

visibility.rb
class Account
  def initialize(balance, pin)
    @balance = balance
    @pin = pin
  end

  def richer_than?(other)
    balance > other.balance      # protected: allowed on another Account
  end

  def unlock(attempt)
    attempt == pin               # private: no receiver needed inside
  end

  protected

  attr_reader :balance

  private

  attr_reader :pin
end

mine = Account.new(100, 1234)
yours = Account.new(50, 9999)
puts mine.richer_than?(yours)     # true
puts mine.unlock(1234)            # true

[:balance, :pin].each do |name|
  mine.public_send(name)
rescue NoMethodError => e
  puts e.message
end
# protected method 'balance' called for an instance of Account
# private method 'pin' called for an instance of Account

Calling a private setter from inside the class needs an explicit self., as in self.mode = :heating, because a bare mode = :heating is a local variable. Since Ruby 2.7, self. is accepted in front of any private method, not only setters.

Readers can leak mutable state

attr_reader returns the very object stored in the instance variable, not a copy. For numbers and symbols that is harmless. For an array, hash or string, the caller can change the object in place, which skips every setter and every rule you wrote. Return a frozen copy from a hand-written reader and offer add methods that enforce the rules. dup copies only the container, so elements that are themselves mutable can still be changed through the copy.

leaky_reader.rb
class Cart
  attr_reader :items

  def initialize
    @items = []
  end

  def add(item)
    @items << item
    self
  end
end

cart = Cart.new.add("pen")
cart.items << "oops"                 # bypasses add completely
p cart.items                         # ["pen", "oops"]

class SafeCart
  def initialize
    @items = []
  end

  def add(item)
    @items << item
    self
  end

  def items
    @items.dup.freeze
  end
end

safe = SafeCart.new.add("pen")
begin
  safe.items << "oops"
rescue FrozenError => e
  puts e.message                     # can't modify frozen Array: ["pen"]
end
p safe.items                         # ["pen"]

In real projects

Where this shows up in real projects

In Rails, every database column becomes a getter and setter on a model, and overriding the setter is the standard way to normalise input: a User model can define email= to downcase and strip the address before it is stored, so a lookup for the same address always matches. Form objects and service objects often use attr_accessor for virtual attributes that are never saved, and tests use attr_reader to expose the one value they need to assert on without opening the whole object up.

Outside Rails the same ideas guard configuration objects, money and date value objects, and API clients that keep a token or a base URL. Making the writer private, or leaving it out entirely, is how a library says that a value is fixed once the object exists. For small bundles of data that never change, Struct and Data.define (Ruby 3.2 and later) generate readers for you, and Data instances are immutable, so no setter exists at all.

Common mistakes

Common mistakes

1. Assigning to a local variable instead of calling the setter

Inside a method, age = value does not call age=. Ruby sees an assignment to a name it has not met, creates a local variable and throws it away when the method ends, so the validation never runs and @age keeps its old value, often nil. Write self.age = value, or assign to @age directly only when you really mean to skip the setter.

2. Leaving a public attr_* line below private

If you add attr_reader :name after a bare private line, the reader is private, and calling it from outside raises "private method 'name' called for an instance of ...". Keep the public attr_* lines above private and gather only the attributes that really are private in a section at the bottom of the class.

3. Believing attr_reader makes the object read-only

attr_reader only blocks assignment such as obj.items = .... It does not stop callers from pushing into the array it returns with <<, so the validation you wrote can be bypassed. Return a frozen copy for collections.

4. Misspelling the instance variable name

Writing @nmae = clean makes Ruby quietly create a second instance variable, and reading an instance variable that was never set just gives nil. So when a reader returns nil unexpectedly, check the instance variable spelling first; using the attr_* macros shrinks the surface where this typo can happen.

Best practices

Best practices

  • Start with attr_reader and add a writer only when outside code genuinely needs to change the value.
  • Put the rules in the setter and have initialize call that setter, so the rules live in exactly one place.
  • When a change has meaning, prefer a verb-named method such as deposit or rename over a raw writer.
  • Return frozen copies of arrays and hashes so callers cannot quietly edit your object from outside.

Mini challenge

Mini challenge: a Thermostat

Write a Thermostat class with a validating setter for the target temperature and a private writer so the mode cannot be changed from outside.

  • target= accepts only a number from 10 to 30 and otherwise raises ArgumentError "target must be 10-30, got X"
  • Store the accepted value rounded to the nearest 0.5 (22.3 becomes 22.5)
  • initialize goes through the setter, and mode starts as :idle
  • heat_to(temp) sets the target and switches mode to :heating, and mode= must be private
thermostat.rb
class Thermostat
  # TODO: public readers for target and mode

  def initialize(target)
    # TODO: go through the validating setter
    @mode = :idle
  end

  # TODO: def target=(value) - validate 10..30, store rounded to 0.5

  def heat_to(temp)
    # TODO: set the target and the mode through the setters
  end

  # TODO: make the mode writer private
end

# TODO: heat_to(22.3), then try target = 45 and a direct mode = :off

Expected: Expected output: target=22.5 mode=heating rejected: target must be 10-30, got 45 blocked: private method 'mode=' called for an instance of Thermostat

Show hint

Round to the nearest 0.5 with (value * 2).round / 2.0. Declare the private writer as attr_writer :mode below private, and remember that heat_to must call it as self.mode = :heating.

Show solution
thermostat.rb
class Thermostat
  attr_reader :target, :mode

  def initialize(target)
    self.target = target
    @mode = :idle
  end

  def target=(value)
    unless value.is_a?(Numeric) && value.between?(10, 30)
      raise ArgumentError, "target must be 10-30, got #{value.inspect}"
    end

    @target = (value * 2).round / 2.0
  end

  def heat_to(temp)
    self.target = temp
    self.mode = :heating
    self
  end

  private

  attr_writer :mode
end

thermostat = Thermostat.new(18)
thermostat.heat_to(22.3)
puts "target=#{thermostat.target} mode=#{thermostat.mode}"

begin
  thermostat.target = 45
rescue ArgumentError => e
  puts "rejected: #{e.message}"
end

begin
  thermostat.mode = :off
rescue NoMethodError => e
  puts "blocked: #{e.message}"
end

Quick quiz 1 / 3

With class Cat; attr_writer :name; end, what happens when you run c = Cat.new; c.name = "Tom"; puts c.name?

Quick quiz 2 / 3

After class Vault; private; attr_reader :code; end, what does Vault.new.code do?

Quick quiz 3 / 3

What is the bug in def age=(value); raise ArgumentError, "negative" if value < 0; age = value; end?

What to remember

  • attr_reader, attr_writer and attr_accessor generate getter and setter methods; a setter is an ordinary method whose name ends in =.
  • Write def age=(value) yourself when a value needs rules, and call it inside the class as self.age = value, because age = value is a local variable.
  • private and protected affect every def and attr_* line below them, and you can be precise with names, as in private attr_reader :x.
  • A reader that returns a mutable object lets callers edit it from outside, so return a frozen copy for collections.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Getters & Setters | Thuta Learning