Ruby Language Subclasses


Example

Inheritance allows classes to define specific behaviour based on an existing class.

class Animal
  def say_hello
    'Meep!'
  end

  def eat
    'Yumm!'
  end
end

class Dog < Animal
  def say_hello
    'Woof!'
  end
end

spot = Dog.new
spot.say_hello # 'Woof!'
spot.eat       # 'Yumm!'

In this example:

  • Dog Inherits from Animal, making it a Subclass.
  • Dog gains both the say_hello and eat methods from Animal.
  • Dog overrides the say_hello method with different functionality.