Bird
Raised Fist0
RubyConceptBeginner · 3 min read

What is attr_accessor in Ruby: Simple Explanation and Example

attr_accessor in Ruby is a shortcut to create both getter and setter methods for instance variables in a class. It lets you read and write object properties easily without writing separate methods.
⚙️

How It Works

Imagine you have a box (an object) with a label (an instance variable) inside it. Normally, to see what's inside or change the label, you need special keys (methods) to open or update it. attr_accessor automatically gives you these keys: one to read the label (getter) and one to change it (setter).

This means you don't have to write separate methods to get or set the value of an instance variable. Ruby creates these methods behind the scenes, making your code shorter and easier to read.

💻

Example

This example shows how attr_accessor creates getter and setter methods for a person's name.

ruby
class Person
  attr_accessor :name
end

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

When to Use

Use attr_accessor when you want to allow both reading and writing of an object's properties without writing extra code. It's great for simple data objects like models or settings where you need easy access to values.

For example, if you have a class representing a book, and you want to change or read its title and author, attr_accessor saves you from writing separate methods for each.

✅

Key Points

  • attr_accessor creates both getter and setter methods automatically.
  • It reduces repetitive code in classes.
  • Use it for simple properties that need to be read and changed.
  • If you only want to read or write, use attr_reader or attr_writer instead.
✅

Key Takeaways

attr_accessor creates easy getter and setter methods for instance variables.
It helps keep your Ruby classes clean and simple by reducing boilerplate code.
Use it when you want to read and write object properties freely.
For read-only or write-only needs, prefer attr_reader or attr_writer.
It is a common Ruby idiom for managing object attributes.