liveBook · Manning

Private setter method

As explained in The Well-Grounded Rubyist, Fourth Edition

A private setter method is a Ruby setter method whose invocation is subject to private-method receiver restrictions, with self permitted as its explicit receiver.

A private setter method is a Ruby setter whose calls follow private-method receiver rules with one special adjustment: assignment syntax requires an explicit receiver, so a private setter must be called with self. section 5.3.1

The rule becomes clear through the contrast between ordinary private methods and setters:

  • Call an ordinary private method without a receiver, as in add_egg. section 5.3.1
  • Write self.dog_years = age * 7 for a private setter; omitting self makes dog_years look like a local variable. section 5.3.1
  • Use private setters to keep internal state updates behind a public operation such as age=. section 5.3.1

Dog years

A Dog can expose age= while keeping dog_years= private. The age= method assigns @age, then calls self.dog_years = years * 7; private :dog_years= prevents outside callers from invoking the setter directly. section 5.3.1

class Dog
  attr_reader :age, :dog_years
  def dog_years=(years) 
    @dog_years = years
  end
  def age=(years)
    @age = years
    self.dog_years = years * 7 1
  end
  private :dog_years=
end

Inspect the complete Dog implementation, including the explicit self receiver and the private declaration. section 5.3.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains receiver restrictions, local-variable ambiguity, syntax, and a complete Dog implementation.
Examples
Uses Dog age= and dog_years= methods to demonstrate a private setter called with self.
What it assumes
Assumes familiarity with private methods and setter-call syntax, while clarifying why setters require special handling.
What you can do after
Apply via Ruby by defining private setters and calling them with self from permitted internal methods.
How it connects
Connects private setters with private methods, explicit receivers, setter methods, method visibility, and encapsulation.

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.