MΓ³dulo 03 Β· Classes & Modules β LecciΓ³n 5 de 6 Β· ~9 min
Inheritance
class Puppy < Dog β one parent, always
Ruby inheritance reads almost exactly like Python's: class Child < Parent. The < means "inherits from" β every method and ivar-setting behavior on Dog is available on Puppy for free:
class Dog
attr_accessor :name
def initialize(name)
@name = name
end
def speak
"#{@name} makes a sound"
end
end
class Puppy < Dog
end
mochi = Puppy.new("Mochi")
puts mochi.speak # Mochi makes a sound β inherited, unchanged
puts mochi.is_a?(Dog) # true β a Puppy IS a DogBe honest about the limit: Ruby is single-inheritance β class Puppy < Dog means exactly one parent, full stop. There's no class Puppy < Dog, Trainable like some languages allow. (Modules, next lesson, are Ruby's answer to needing more than one source of shared behavior.)