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
