liveBook · Manning

Attribute

As explained in The Well-Grounded Rubyist, Fourth Edition

A property is an attribute or quality associated with an entity or object.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains readers, writers, instance variables, shortcuts, mutability, and runtime inspection without exhaustive API detail.
Examples
Demonstrates ticket properties, Struct and Data records, and a Person object inspected before and after assigning an accessor.
What it assumes
Assumes basic Ruby objects and classes while teaching instance variables, accessor methods, and read/write terminology.
What you can do after
Apply it via Ruby accessors to define, expose, mutate, and inspect object state.
How it connects
Connects attributes with instance variables, methods, classes, modules, inheritance, and object state.

Also explained in

Compare how 26 books explain attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.