liveBook · Manning

Accessor method

As explained in The Well-Grounded Rubyist, Fourth Edition

An attribute accessor method is a method that provides access to an object's attribute by reading or writing its value.

A ticket can hold a venue, date, and price in instance variables. Accessor methods give other code a way to read or change that state: a reader returns a value, while a writer accepts a new one. Ruby convention names a reader after the attribute, such as `venue`, rather than `get_venue`. section 3.2.1 section 3.3

Reading and changing a ticket’s price

```ruby class Ticket def initialize(venue, date) @venue = venue @date = date end def price @price end def price=(amount) @price = amount end end ticket = Ticket.new("Town Hall", "2025-11-12") ticket.price = 63.00 ticket.price # => 63.0 ``` The reader returns `@price` because it is the method’s last expression. The writer stores its argument in that instance variable. section 3.2.1 section 3.3.1

`ticket.price = 63.00` looks like assignment, but it calls the method `price=` on `ticket` with `63.00` as its argument. The same call can be written `ticket.price=(63.00)`. This assignment-like syntax is available to methods whose names end in `=`; it does not make `ticket.price` a variable. section 3.3.1 section 3.3.2

A writer need not blindly store its argument. A `price=` method can reject a price with extra decimal places, and a `year=` method can convert a two-digit year into a four-digit one. The assignment-like spelling does not guarantee sensible behavior: the method’s implementation determines what happens. section 3.3.3

For straightforward accessors, `attr_reader :venue, :date` creates readers, `attr_writer :price` creates a writer, and `attr_accessor :price` creates both a reader and a writer. Write the methods out when access needs custom behavior. Like other instance methods, accessors can also be inherited by subclasses. section 3.4.1 section 3.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through hand-written readers, assignment-style writers, validation, and automatic generation with `attr_*` methods.
Examples
Uses ticket prices, validated dollar amounts, normalized years, and inherited publication attributes.
What it assumes
Builds on Ruby classes, methods, and object creation while explaining how initialization stores state in instance variables.
What you can do after
Build it from scratch with reader and writer methods, or apply Ruby’s `attr_reader`, `attr_writer`, and `attr_accessor`.
How it connects
Connects accessor methods to instance variables, object initialization, syntactic sugar, and inheritance.

Also explained in

Compare how 13 books explain accessor method →

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.