Logo

What is attr_accessor in Ruby?

In Ruby, the attr_accessor method is a powerful shortcut for creating both “getter” and “setter” methods for instance variables. Rather than manually writing out two separate methods to read and write a variable, attr_accessor automates the process with a single line of code. Whether you’re a beginner coming from a background in languages like Java or Python, or a seasoned developer looking to save time, understanding attr_accessor is key to writing clean, maintainable Ruby classes.

What Is attr_accessor?

Ruby provides three primary methods for generating getter and setter methods:

  • attr_reader: Creates a getter method (read-only access)
  • attr_writer: Creates a setter method (write-only access)
  • attr_accessor: Creates both getter and setter methods (read/write access)

When you use attr_accessor :variable, you’re instructing Ruby to automatically create:

  1. Getter (variable): Allows you to retrieve the value of @variable.
  2. Setter (variable=): Allows you to set the value of @variable.

Example

class Book attr_accessor :title def initialize(title) @title = title end end my_book = Book.new("Ruby Essentials") puts my_book.title # => "Ruby Essentials" my_book.title = "Advanced Ruby" puts my_book.title # => "Advanced Ruby"

Without attr_accessor, you’d have to write both:

class Book def initialize(title) @title = title end # Getter def title @title end # Setter def title=(new_title) @title = new_title end end

Clearly, attr_accessor makes your code more concise and easier to maintain.

attr_reader vs. attr_writer vs. attr_accessor

  • attr_reader :title: Defines only a getter method, so the variable can be read but not changed externally.
  • attr_writer :title: Defines only a setter method, so the variable can be changed externally but not read (often useful for sensitive data).
  • attr_accessor :title: Defines both a getter and a setter, allowing full read/write access.

Choose the right method based on how you want other parts of your code to interact with an object’s data. For instance, if a particular attribute shouldn’t be modified once set, stick with attr_reader. If you want full flexibility, use attr_accessor.

Best Practices

  1. Encapsulation
    Even though attr_accessor is convenient, don’t overuse it. Exposing too many variables to external modification can lead to tight coupling. Only provide getters and setters for attributes you genuinely need to be accessible outside the class.

  2. Validations
    If you have logic or validations that need to run whenever an attribute is set, you may prefer manually defining a setter method instead of using attr_accessor. For example:

    def title=(new_title) raise "Title cannot be blank" if new_title.strip.empty? @title = new_title end
  3. Avoid Overriding Automatically Generated Methods
    If you define a custom title or title= method, you’ll override the behavior provided by attr_accessor. Make sure that’s intentional and not a bug.

  4. Immutable Objects
    Some Rubyists favor immutable objects for certain designs. In such cases, you might only use attr_reader and pass all data through the constructor, never reassigning attributes.

Further Learning

Strengthen Your Coding Foundations

To become proficient in Ruby (or any language), you need a solid grasp of coding patterns and algorithms. Check out:

Explore System Design

If you’re aiming for higher-level roles or want to understand how Ruby applications fit into large-scale architectures, dive into system design:

Additionally, the System Design Primer: The Ultimate Guide on the DesignGurus.io blog offers free insights into designing scalable, reliable systems. You can also get personalized feedback from ex-FAANG engineers by booking a Coding Mock Interview or System Design Mock Interview.

Conclusion

attr_accessor is a convenient metaprogramming helper in Ruby that encapsulates the boilerplate needed for reading and writing instance variables. By balancing convenience with sound encapsulation principles, you’ll write elegant, maintainable Ruby code. As you continue your Ruby journey, remember that well-designed classes go beyond simple getters and setters—focus on object-oriented design, coding patterns, and system design concepts to become a truly proficient Ruby developer.

CONTRIBUTOR
TechGrind