Bird
Raised Fist0
RubyConceptBeginner · 3 min read

What is attr_writer in Ruby: Simple Explanation and Example

attr_writer in Ruby is a method that creates a setter method for an instance variable, allowing you to change its value from outside the object. It helps you write cleaner code by automatically generating these setter methods without writing them manually.
⚙️

How It Works

Imagine you have a box with a label on it. You want to be able to change what the label says without opening the box. In Ruby, instance variables are like the contents inside the box, and setter methods let you change the label from outside.

attr_writer automatically creates these setter methods for you. Instead of writing a method to change a variable's value, you just tell Ruby to make one with attr_writer. This keeps your code simple and easy to read.

💻

Example

This example shows how attr_writer creates a setter method to change an object's instance variable.

ruby
class Person
  attr_writer :name

  def initialize(name)
    @name = name
  end

  def display_name
    "Name: #{@name}"
  end
end

person = Person.new("Alice")
puts person.display_name  # Shows initial name
person.name = "Bob"     # Uses setter created by attr_writer
puts person.display_name  # Shows updated name
Output
Name: Alice Name: Bob
🎯

When to Use

Use attr_writer when you want to allow changing an object's instance variable from outside the object but do not need to read it directly. For example, if you want to let others update a value but keep the reading method private or custom, attr_writer is perfect.

It is common in cases where you want to control how data is accessed and modified separately, like setting a password or updating a configuration value without exposing it directly.

✅

Key Points

  • attr_writer creates only setter methods (to write/change values).
  • It does not create getter methods (to read values).
  • Use it to keep your code clean and avoid writing repetitive setter methods.
  • It helps control how instance variables are modified from outside the object.
✅

Key Takeaways

attr_writer automatically creates setter methods for instance variables.
It allows changing object data from outside without manually writing setter methods.
Use it when you want to allow writing but not direct reading of variables.
It keeps your Ruby code clean and easy to maintain.