What is Inheritance in Ruby: Simple Explanation and Example
inheritance is a way for one class to take on the properties and behaviors of another class. It allows a new class (child) to reuse code from an existing class (parent), making programs easier to write and maintain.How It Works
Inheritance in Ruby works like a family tree. Imagine a child learning skills from their parent. In programming, a child class inherits methods and variables from a parent class, so it doesn't have to write them again.
This means the child class can use or change what it inherits. If the child needs something new, it can add its own methods or override the parent's methods to behave differently.
This helps keep code simple and organized, just like how children build on what their parents taught them.
Example
This example shows a Animal class with a method, and a Dog class that inherits from Animal. The Dog class can use the Animal method and also add its own.
class Animal def speak "I make a sound" end end class Dog < Animal def speak "Woof!" end def fetch "I fetch the ball" end end animal = Animal.new puts animal.speak dog = Dog.new puts dog.speak puts dog.fetch
When to Use
Use inheritance when you have classes that share common features but also have their own unique parts. For example, in a game, you might have a general Character class and specific classes like Wizard or Warrior that inherit from it.
This saves time because you write shared code once and keep your program clean and easy to update.
Key Points
- Inheritance lets a class reuse code from another class.
- The child class can add or change behaviors inherited from the parent.
- It helps organize code and avoid repetition.
- In Ruby, use
<to show inheritance (e.g.,class Dog < Animal).
Key Takeaways
< symbol.