Skip to content

Interfaces

Table of Contents

If you are accustomed to working with Java, C#, C++, Go, TypeScript, Swift, PHP or Kotlin, then you may be looking for information on Interfaces in Ruby. Sorry to disappoint, but Ruby does not implement interfaces. However, Ruby achieves similar functionality through the use of modules and mixins, along with the concept of duck typing. Here’s a more detailed explanation of how Ruby handles these concepts:

Modules and Mixins

Ruby uses modules to encapsulate methods and constants, and these modules can be mixed into classes using the include or extend keywords. This allows for sharing common functionality across multiple classes.

In this example, the Drivable module provides the drive method, and both Car and Truck classes include this module to gain access to the drive method.

Duck Typing

Ruby follows the principle of duck typing, which means that the type or class of an object is determined by its methods and properties rather than its inheritance from a specific class or implementation of an interface. If an object behaves like a duck (i.e., has the necessary methods), it can be used as a duck.

In this example, the make_animal_speak method accepts any object that responds to the speak method, regardless of the object’s class.

Abstract Classes and Methods

Although Ruby does not have a formal concept of interfaces, you can define abstract methods in a base class that must be implemented by subclasses. This is more of a convention than a language-enforced rule.

In this example, Animal is a base class with an abstract method speak, which raises an error if not implemented by a subclass. Dog and Cat classes implement the speak method, providing the necessary functionality.