Ruby OOP: encapsulation
This course covers how a Ruby class decides which of its methods form its public interface. Using a BankAccount class that charges a withdrawal fee, it shows why leaving internal methods public lets outside code depend on them. It then covers private methods, called with no explicit receiver, and the literal self exception allowed since Ruby 2.7. It explains protected methods, which accept a receiver from inside the same class, compares both through their NoMethodError messages, and applies the same rules to methods generated by attr_accessor.
What you'll learn
- ✓Why every Ruby method is public by default and when to narrow that
- ✓Calling private methods with no explicit receiver
- ✓The literal self exception to private, allowed since Ruby 2.7
- ✓How protected allows a receiver from inside the same class or a subclass
- ✓Telling private and protected apart by their NoMethodError messages
- ✓Setting visibility on methods generated by attr_reader, attr_writer and attr_accessor
Why encapsulation hides implementation
The Ruby variables & assignment course built this class. Read it again with new eyes:
Read the full lesson free →Curriculum
7 lessonsWhy encapsulation hides implementation
Shows how a public service_fee method lets outside code depend on an implementation detail of BankAccount.
private: no explicit receiver
Marks service_fee private and shows that calls without a receiver work while account.service_fee raises NoMethodError.
The self exception to private
Explains why self.service_fee works since Ruby 2.7, while calling it through a variable holding self still fails.
protected: an explicit receiver, from the same class
Makes balance protected so richer_than? can call other.balance, while calls from outside the class raise NoMethodError.
private vs protected, side by side
Compares private and protected side by side, including calls on another instance and from an unrelated class.
attr_accessor's hidden assumption
Shows that attr_writer and attr_accessor generate ordinary public methods, and how a private setter is called.
Putting it together: BankAccount, fully encapsulated
Reviews the finished BankAccount class and traces each visibility choice back to the rule behind it.