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.
module Drivable
def drive
puts "Driving..."
end
end
class Car
include Drivable
end
class Truck
include Drivable
end
car = Car.new
car.drive # Output: Driving...
truck = Truck.new
truck.drive # Output: Driving...
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.
class Dog
def speak
puts "Woof!"
end
end
class Cat
def speak
puts "Meow!"
end
end
def make_animal_speak(animal)
animal.speak
end
dog = Dog.new
cat = Cat.new
make_animal_speak(dog) # Output: Woof!
make_animal_speak(cat) # Output: Meow!
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.
class Animal
def speak
raise NotImplementedError, "This method must be implemented by a subclass"
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
class Cat < Animal
def speak
puts "Meow!"
end
end
dog = Dog.new
cat = Cat.new
dog.speak # Output: Woof!
cat.speak # Output: Meow!
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.