Tsallaka zuwa abun ciki
Justice Tech School

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

How many parents can a class have?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.