Attr_accessor vs attr_reader vs attr_writer in Ruby: Key Differences
attr_reader creates a getter method for reading an instance variable, attr_writer creates a setter method for writing to it, and attr_accessor creates both getter and setter methods for full read-write access.Quick Comparison
This table summarizes the main differences between attr_accessor, attr_reader, and attr_writer in Ruby.
| Feature | attr_reader | attr_writer | attr_accessor |
|---|---|---|---|
| Creates getter method | Yes | No | Yes |
| Creates setter method | No | Yes | Yes |
| Allows reading value | Yes | No | Yes |
| Allows writing value | No | Yes | Yes |
| Use case | Read-only attribute | Write-only attribute | Read-write attribute |
Key Differences
attr_reader defines a method that returns the value of an instance variable, allowing you to read it from outside the object but not change it directly. This is useful when you want to protect the data from being modified.
attr_writer defines a method that lets you set or change the value of an instance variable from outside the object, but it does not provide a way to read the value back. This is less common but useful when you want to allow changes without exposing the current value.
attr_accessor combines both attr_reader and attr_writer, creating getter and setter methods. This gives full access to read and write the instance variable, making it the most flexible option for attributes that need to be both read and modified.
Code Comparison
Here is an example using attr_accessor to create both getter and setter methods for a name attribute.
class Person attr_accessor :name end person = Person.new person.name = "Alice" puts person.name
attr_reader and attr_writer Equivalent
This example shows how to achieve the same functionality as attr_accessor by using attr_reader and attr_writer separately.
class Person attr_reader :name attr_writer :name end person = Person.new person.name = "Alice" puts person.name
When to Use Which
Choose attr_reader when you want to allow reading an attribute but keep it protected from changes outside the class. Use attr_writer when you want to allow setting an attribute but hide its current value. Use attr_accessor when you want to allow both reading and writing the attribute freely.
In most cases, attr_accessor is the simplest choice for attributes that need full access, while attr_reader helps enforce immutability or controlled access.
Key Takeaways
attr_reader for read-only access to instance variables.attr_writer for write-only access to instance variables.attr_accessor for both read and write access.attr_accessor for flexible attribute access.