Inheritance and Messages

In a previous chapter, we saw that when the puts method needs to convert an object to a string, it calls that object’s to_s method. But we’ve also written our own classes that don’t explicitly implement to_s. Despite this, instances of these classes respond successfully when we call to_s on them. How this works has to do with inheritance and how Ruby uses it to determine what method to run when you send a message to an object.

Inheritance allows you to create a class that’s a specialization of another class. This specialized class is called a subclass of the original, and the original is a superclass of the subclass. People also refer to this relationship as child and parent classes.

The basic mechanism of subclassing ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.