0
0
Rubyprogramming~5 mins

Attr_reader, attr_writer, attr_accessor in Ruby

Choose your learning style9 modes available
Introduction

These keywords help you easily create methods to get or set object data without writing extra code.

When you want to read a value from an object safely.
When you want to change a value inside an object.
When you want both reading and writing access to an object's data.
When you want to keep your code short and clean.
When you want to control how object data is accessed or changed.
Syntax
Ruby
class ClassName
  attr_reader :name  # creates a method to read @name
  attr_writer :name  # creates a method to write @name
  attr_accessor :name # creates both read and write methods
end

Use attr_reader for read-only access.

Use attr_writer for write-only access.

Examples
This creates a read-only name method.
Ruby
class Person
  attr_reader :name
  def initialize(name)
    @name = name
  end
end
This allows setting age but not reading it.
Ruby
class Person
  attr_writer :age
end

p = Person.new
p.age = 30
This allows both reading and writing email.
Ruby
class Person
  attr_accessor :email
end

p = Person.new
p.email = "a@b.com"
puts p.email
Sample Program

This program shows how each keyword works: make can only be read, color can be read and changed, and year can only be changed.

Ruby
class Car
  attr_accessor :color
  attr_reader :make
  attr_writer :year

  def initialize(make, color, year)
    @make = make
    @color = color
    @year = year
  end
end

car = Car.new("Toyota", "red", 2020)
puts car.make      # read only
puts car.color     # read and write
car.color = "blue"
puts car.color
car.year = 2021   # write only
# puts car.year    # would cause error because no reader
OutputSuccess
Important Notes

If you try to read a write-only attribute, Ruby will give an error.

Using these keywords keeps your code shorter and easier to read.

You can use them with many attributes at once, like attr_accessor :a, :b, :c.

Summary

attr_reader creates a method to read an attribute.

attr_writer creates a method to write an attribute.

attr_accessor creates both read and write methods.