juniorRuby
What are attr_reader, attr_writer, and attr_accessor?
Updated May 17, 2026
Short answer
These are built-in macro methods that automatically generate getter and setter methods for instance variables to avoid boilerplates.
Deep explanation
In Ruby, instance variables cannot be accessed from outside the object instance directly. You must define explicit getter and setter methods. To automate this, Ruby provides attr_reader (creates a getter), attr_writer (creates a setter), and attr_accessor (creates both getter and setter).
Real-world example
Defining domain models where properties need safe exposure without writing repetitive ruby boilerplates for every field.
Common mistakes
- Using `attr_accessor` blindly for all fields, exposing internal states or sensitive fields (like password tokens) that should remain read-only or entirely private.
Follow-up questions
- What do these attr_* macros return when executed?
- How are these macros actually implemented behind the scenes?