Inheritance and super in Ruby
Subclassing with < and extending a parent method with super.
class Animal
def initialize(name)
@name = name
end
def speak
"#{@name} makes a sound"
end
end
class Dog < Animal
# super calls the parent's version of the same method
def speak
"#{super}: woof"
end
end
puts Animal.new("generic").speak
puts Dog.new("rex").speak
How it works
Dog < Animalinheritsinitializeand everything else.- The subclass overrides
speakwith its own version. supercalls the parent's method and builds on its result.
Keywords and builtins used here
AnimalDogclassdefendinitializenameputsspeaksuper
The run, in numbers
- Lines
- 19
- Characters to type
- 263
- Tokens
- 58
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 39 seconds.
Step 2 of 3 in Classes & modules, step 20 of 29 in Language basics.