Ruby Language Inheritance Refactoring existing classes to use Inheritance

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Let's say we have two classes, Cat and Dog.

class Cat
  def eat
    die unless has_food?
    self.food_amount -= 1
    self.hungry = false
  end
  def sound
    puts "Meow"
  end
end

class Dog
  def eat
    die unless has_food?
    self.food_amount -= 1
    self.hungry = false
  end
  def sound
    puts "Woof"
  end
end

The eat method is exactly the same in these two classes. While this works, it is hard to maintain. The problem will get worse if there are more animals with the same eat method. Inheritance can solve this problem.

class Animal
  def eat
    die unless has_food?
    self.food_amount -= 1
    self.hungry = false
  end
  # No sound method
end

class Cat < Animal
  def sound
    puts "Meow"
  end
end

class Dog < Animal
  def sound
    puts "Woof"
  end
end

We have created a new class, Animal, and moved our eat method to that class. Then, we made Cat and Dog inherit from this new common superclass. This removes the need for repeating code



Got any Ruby Language Question?