Start Coding

Topics

Ruby attr_* Methods

Ruby's attr_* methods are powerful tools for simplifying getter and setter methods in your classes. These methods provide a concise way to define accessors for instance variables, reducing boilerplate code and improving readability.

Types of attr_* Methods

There are three main attr_* methods in Ruby:

  • attr_reader: Creates a getter method
  • attr_writer: Creates a setter method
  • attr_accessor: Creates both getter and setter methods

attr_reader

The attr_reader method creates a getter method for the specified instance variable. It allows you to read the value of the instance variable without directly accessing it.


class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

person = Person.new("Alice")
puts person.name  # Output: Alice
    

attr_writer

The attr_writer method creates a setter method for the specified instance variable. It allows you to set the value of the instance variable without directly modifying it.


class Person
  attr_writer :age

  def initialize(age)
    @age = age
  end
end

person = Person.new(30)
person.age = 31
    

attr_accessor

The attr_accessor method creates both getter and setter methods for the specified instance variable. It combines the functionality of attr_reader and attr_writer.


class Person
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end
end

person = Person.new("Bob", 25)
puts person.name  # Output: Bob
person.age = 26
puts person.age   # Output: 26
    

Benefits of Using attr_* Methods

  • Reduces code duplication
  • Improves readability and maintainability
  • Follows Ruby's principle of convention over configuration
  • Allows for easy modification of accessor behavior

Best Practices

When working with attr_* methods, consider the following best practices:

  1. Use attr_reader for read-only attributes
  2. Use attr_writer sparingly, as it's often better to have more control over setting values
  3. Use attr_accessor when you need both read and write access
  4. Group attr_* declarations at the beginning of your class definition for better organization
  5. Consider using Ruby Encapsulation principles when deciding which attributes to expose

Related Concepts

To deepen your understanding of Ruby's object-oriented features, explore these related topics:

By mastering attr_* methods, you'll write cleaner, more maintainable Ruby code. These methods are essential tools in any Ruby developer's toolkit, simplifying the process of working with object attributes.