Ruby Inheritance
A class inherits from one parent with <. super calls the parent method, and methods can be overridden. Everything inherits from Object.
Example
class Animal
def initialize(name) = @name = name
def speak = "..."
def to_s = "#{self.class}: #{@name} says #{speak}"
end
class Dog < Animal
def speak = "Woof"
end
class Cat < Animal
def speak = super + "Meow"
end
puts Dog.new("Rex"), Cat.new("Tom")Result
Dog: Rex says Woof Cat: Tom says ...Meow
Exercise
Inherit symbol.
class Dog Animal
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.