Junior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...