Inheritance in Ruby: Extending Classes


Introduction to Inheritance

Inheritance is a core concept of Object-Oriented Programming (OOP). It allows you to create new classes that are based on existing classes. In Ruby, you can extend classes to inherit their attributes and methods. In this guide, we'll explore how inheritance works in Ruby and how to extend classes effectively.


Defining a Base Class

You can create a base class by defining a class with attributes and methods. These attributes and methods can be inherited by other classes. Here's an example of a base class:


class Animal
def initialize(name)
@name = name
end
def speak
puts "#{@name} makes a sound."
end
end

In this example, the Animal class defines an initialize constructor and a speak method.


Creating a Subclass

You can create a subclass that inherits from the base class by using the < symbol. The subclass can access the attributes and methods of the base class. Here's an example:


class Dog < Animal
def speak
puts "#{@name} barks loudly."
end
end

In this example, the Dog class inherits from the Animal class and overrides the speak method.


Creating and Using Subclass Objects

You can create objects from the subclass, and they inherit the attributes and methods of the base class. Here's how you create and use a Dog object:


animal = Animal.new("Generic Animal")
dog = Dog.new("Buddy")
animal.speak
dog.speak

The Dog object inherits the speak method from the Animal class but overrides it to provide its behavior.


Conclusion

Inheritance is a powerful mechanism for creating hierarchies of classes and reusing code. By understanding how to extend classes and create subclasses in Ruby, you can build more organized and modular applications.


Practice inheritance in your Ruby programs to become a proficient Ruby developer. For more information, refer to the official Ruby documentation.


Happy coding!