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.
There are three main attr_* methods in Ruby:
attr_reader: Creates a getter methodattr_writer: Creates a setter methodattr_accessor: Creates both getter and setter methodsThe 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
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
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
When working with attr_* methods, consider the following best practices:
attr_reader for read-only attributesattr_writer sparingly, as it's often better to have more control over setting valuesattr_accessor when you need both read and write accessattr_* declarations at the beginning of your class definition for better organizationTo 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.