Thuta Learning
AdvancedProgrammingbeginner

Getters & Setters

Relax. We'll talk through this in plain words — no textbook voice.

You shouldn't call instance variables directly from outside a class. Ruby makes it easy to create getter/setter methods with attr_reader, attr_writer, and attr_accessor.

ruby
class Car
  attr_accessor :brand
  attr_reader :color

  def initialize(brand, color)
    @brand = brand
    @color = color
  end
end

my_car = Car.new("Honda", "Blue")
my_car.brand = "Mazda"

puts my_car.brand
puts my_car.color

attr_accessor :brand lets you both read and write brand. attr_reader :color only allows reading color.

You should see
Mazda Blue

Info

For data you don't want changed, use attr_reader. Not exposing your public API more than necessary is just good design.

Easy traps

  • If only attr_reader :color is defined, calling my_car.color = "Red" raises a NoMethodError, since there's no setter.
Getters & Setters | Thuta Learning