How To Extend A Class In Ruby

In this blog post, we will explore the concept of extending a class in Ruby, a powerful feature of Ruby’s object-oriented programming paradigm. Extending a class allows us to add new methods, or override existing ones, of an existing class without modifying the original class itself.

Understanding Class Extension

Extending a class in Ruby can be achieved using the extend keyword, which allows us to add the methods defined in a module to an existing class. This is different from inheriting a class, as in inheritance we create a new class that inherits the properties and methods of a parent class, while in class extension, we add methods to an existing class directly.

Let’s take a look at a simple example to understand how class extension works in Ruby.

Example: Extending a Class with a Module

Suppose we have a class called Car which has a method start_engine:

class Car
  def start_engine
    puts "Engine started!"
  end
end

We want to add a new method called stop_engine to this class, but without modifying the original Car class. We can do this by defining a new module with the stop_engine method and then extending the Car class with this module:

module CarExtension
  def stop_engine
    puts "Engine stopped!"
  end
end

class Car
  extend CarExtension
end

Now, the Car class has both the start_engine and stop_engine methods:

car = Car.new
car.start_engine
car.stop_engine

This will output:

Engine started!
Engine stopped!

Overriding Existing Methods

In addition to adding new methods, we can also use class extension to override existing methods in a class. Let’s say we want to change the behavior of the start_engine method in the Car class:

module CarExtension
  def start_engine
    puts "Engine started with an extension!"
  end
end

class Car
  extend CarExtension
end

Now, when we call the start_engine method on a Car object, it will output:

Engine started with an extension!

Conclusion

In this blog post, we explored the concept of extending a class in Ruby using the extend keyword with the help of a module. We learned how to add new methods and override existing methods in an existing class without modifying its original definition. This powerful feature allows us to create more flexible and reusable code in Ruby’s object-oriented programming paradigm.