An attribute is a property of an object whose value can be read, written, or both through the object. In Ruby, attributes are reader and writer methods wrapped around instance variables; Ruby has no separate attribute construct. section 3.4
Ruby commonly represents attributes through:
- Reader methods, such as date, venue, and price, return an attribute value. section 3.4
- Writer methods, such as price=, assign an attribute value. section 3.4
- The attr_* method family generates these methods concisely, while instance variables store the object’s state. section 3.4 section 3.9
Mutable and immutable attribute sets
Struct.new(:name, :id, :salary) creates attributes that can be read and changed, so emp_1.salary *= 1.15 works. Data.define(:customer_id, :amount) creates readable attributes without writer methods, so assigning inv_1.amount raises an undefined-method error. section 3.1.3
Attributes expose selected object state without requiring direct access to instance variables. A property can also describe a shared characteristic better modeled in a module than in an inheritance relationship. section 3.9 section 4.4.1
class Person
attr_accessor :name, :age
def initialize(name)
@name = name
end
end
bob = Person.new("Bob")
p bob.instance_variables #1
bob.age = 50
p bob.instance_variables #2
Inspect how attr_accessor creates accessors and how assigning age causes @age to appear among the object’s instance variables. section 15.3.2

























