Bird
Raised Fist0
RubyComparisonBeginner · 3 min read

Attr_accessor vs attr_reader vs attr_writer in Ruby: Key Differences

In Ruby, 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.

Featureattr_readerattr_writerattr_accessor
Creates getter methodYesNoYes
Creates setter methodNoYesYes
Allows reading valueYesNoYes
Allows writing valueNoYesYes
Use caseRead-only attributeWrite-only attributeRead-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.

ruby
class Person
  attr_accessor :name
end

person = Person.new
person.name = "Alice"
puts person.name
Output
Alice
↔️

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.

ruby
class Person
  attr_reader :name
  attr_writer :name
end

person = Person.new
person.name = "Alice"
puts person.name
Output
Alice
🎯

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

Use attr_reader for read-only access to instance variables.
Use attr_writer for write-only access to instance variables.
Use attr_accessor for both read and write access.
Choosing the right accessor improves encapsulation and code clarity.
Most common use is attr_accessor for flexible attribute access.