Ruby: Attribute Accessors

Attribute accessors in Ruby are methods that allow you to read and write instance variables of an object. They are commonly used for creating getter and setter methods for object properties. Here are some tips and tricks for using attribute accessors effectively.

Leveraging attr_accessor, attr_reader, and attr_writer

Ruby furnishes us with three indispensable methods for defining attribute accessors:

  • attr_accessor creates both getter and setter methods for an instance variable.
  • attr_reader creates a getter method only.
  • attr_writer creates a setter method only.


Let’s illustrate their usage through an example: