Inheritance, Mixins, and Design
Inheritance and mixed-in modules both allow you to write code in one place and use that code in multiple classes. So, when do you use each?
As with most questions of design, the answer is, well…it depends. But over the years, developers have come up with some general guidelines to help us decide.
First, let’s look at subclassing. Classes in Ruby are related to the idea of types. It would be natural to say that "cat" is a string and [1, 2] is an array. And that’s another way of saying that the class of "cat" is String and the class of [1, 2] is Array. When we create our own classes, you can think of it as adding new types to the language. And when we subclass either a built-in class or our own class, we’re creating ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access