Chapter 9. Objects and Classes
Ruby is an object-oriented programming language; this chapter will show you what that really means. Like all modern languages, Ruby supports object-oriented notions like classes, inheiritance, and polymorphism. But Ruby goes further than other languages you may have used. Some languages are strict and some are permissive; Ruby is one of the most permissive languages around.
Strict languages enforce strong typing, usually at compile time: a variable defined as an array can’t be used as another data type. If a method takes an array as an argument, you can’t pass in an array-like object unless that object happens to be a subclass of the array class or can be converted into an array.
Ruby enforces dynamic typing, or duck typing (“if it quacks like a duck, it is a duck”). A strongly typed language enforces its typing everywhere, even when it’s not needed. Ruby enforces its duck typing relative to a particular task. If a variable quacks like a duck, it is one—assuming you wanted to hear it quack. When you want “swims like a duck” instead, duck typing will enforce the swimming, and not the quacking.
Here’s an example. Consider the following three classes, Duck, Goose, and DuckRecording:
classDuckdefquack'Quack!'enddefswim'Paddle paddle paddle…'endendclassGoosedefhonk'Honk!'enddefswim'Splash splash splash…'endendclassDuckRecordingdefquackplayenddefplay'Quack!'endend
If Ruby were a strongly typed language, a method that told ...
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