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:

class Duck
  def quack
    'Quack!'
  end

  def swim
    'Paddle paddle paddle…'
  end
end

class Goose
  def honk
    'Honk!'
  end
  def swim
    'Splash splash splash…'
  end
end

class DuckRecording
  def quack
    play
  end

  def play
    'Quack!'
  end
end

If Ruby were a strongly typed language, a method that told ...

Get Ruby Cookbook, 2nd Edition 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.