TExcelTAD
Home › Ruby › Ruby Instance Variables & Accessors

Ruby Instance Variables & Accessors

An object's instance variables are hidden from the outside world. The only way in is through methods. Methods that read a value are called getters (readers), methods that change one are setters (writers). Ruby can generate both for you with attr_reader, attr_writer and attr_accessor.

Writing getters and setters by hand

ruby · try it yourself
class Book
  def initialize(title)
    @title = title
  end

  def title          # getter
    @title
  end

  def title=(value)  # setter
    @title = value
  end
end

b = Book.new("Emma")
puts b.title
b.title = "Persuasion"
puts b.title
Emma
Persuasion

The setter's name ends with =. Ruby lets you call it with normal assignment syntax: b.title = "..." is really b.title=("...").

attr_reader, attr_writer, attr_accessor

Writing those methods by hand quickly gets repetitive. These class-level helpers generate them:

Helper Generates
attr_reader :name getter name
attr_writer :name setter name=
attr_accessor :name both
ruby · try it yourself
class Player
  attr_reader :name          # read-only from outside
  attr_accessor :score       # readable and writable
  attr_writer :nickname      # write-only (rare)

  def initialize(name)
    @name = name
    @score = 0
  end

  def label
    @nickname ? "#{@name} (#{@nickname})" : @name
  end
end

pl = Player.new("Hana")
pl.score += 10
pl.score += 5
pl.nickname = "Ace"
puts "#{pl.label}: #{pl.score}"

begin
  pl.name = "Someone else"
rescue NoMethodError => e
  puts "Can't rename: #{e.message}"
end
Hana (Ace): 15
Can't rename: undefined method 'name=' for an instance of Player

Choose the smallest access you need: prefer attr_reader and add writers only when outside code really must change the value.

Validating in a custom setter

A hand-written setter can check or convert the value before storing it:

ruby · try it yourself
class Thermostat
  attr_reader :target

  def initialize
    @target = 20
  end

  def target=(degrees)
    raise ArgumentError, "must be between 5 and 30" unless (5..30).cover?(degrees)
    @target = degrees
  end
end

t = Thermostat.new
t.target = 23
p t.target

begin
  t.target = 90
rescue ArgumentError => e
  puts "Rejected: #{e.message}"
end
p t.target
23
Rejected: must be between 5 and 30
23

Use self. when calling a setter inside the class

Inside a method, score = 5 creates a local variable, it does not call the setter. To call the setter you must write self.score = 5:

ruby · try it yourself
class Game
  attr_accessor :score

  def initialize
    @score = 0
  end

  def broken_reset
    score = 100   # just a local variable!
  end

  def reset
    self.score = 100
  end
end

g = Game.new
g.broken_reset
p g.score
g.reset
p g.score
0
100

Getters don't need self.: inside the class, score alone calls the getter (when there's no local variable with that name).

Computed attributes

A getter doesn't have to return a stored variable — it can calculate something:

ruby · try it yourself
class Rectangle
  attr_accessor :width, :height

  def initialize(width, height)
    @width = width
    @height = height
  end

  def area = width * height
  def square? = width == height
end

r = Rectangle.new(4, 6)
p r.area
p r.square?
r.width = 6
p r.area
p r.square?
24
false
36
true

To the caller, r.area looks exactly like r.width — that's the point. You can change how a value is produced without changing the code that uses it.

Instance variables you didn't set are nil

Reading an instance variable that was never assigned gives nil, not an error. Typos can therefore slip by silently — another reason to go through accessors:

ruby · try it yourself
class Note
  def initialize(text)
    @text = text
  end

  def preview
    @txt.to_s[0, 10]   # typo: @txt instead of @text
  end

  def fixed_preview
    @text[0, 10]
  end
end

n = Note.new("Remember the milk and eggs")
p n.preview
p n.fixed_preview
""
"Remember t"

Test yourself

Which helper creates both a getter and a setter?

  1. attr_reader
  2. attr_writer
  3. attr_accessor
  4. attr_both

Inside an instance method, how do you call the setter name=?

  1. name = "x"
  2. self.name = "x"
  3. @name("x")
  4. set_name "x"

What does reading an unassigned instance variable return?

  1. An error
  2. 0
  3. nil
  4. false