Inheritance and Modules
class Cat < Animal makes Cat inherit from Animal — ordinary single inheritance, the same idea Java, C#, and Kotlin all have. super, called from an overriding method, invokes the parent class's version of that same method. None of this is new. What's distinctive is module/include: a module can't be instantiated on its own, but include mixes all of its methods directly into a class, as if they'd been defined there. A class can include any number of modules, which is effectively Ruby's version of multiple inheritance — genuinely unlike Java/C#/Kotlin's single-inheritance-plus-interfaces model (an interface has no method bodies to mix in) or Rust's traits (which don't share this exact mental model of "inject these methods into my class body").
module Greetable
def greet
"Hi, I'm #{name}"
end
end
class Animal
attr_reader :name
def initialize(name)
@name = name
end
def speak
"..."
end
end
class Cat < Animal
include Greetable
def speak
super + " Meow!"
end
end
c = Cat.new("Tom")
puts c.speak
puts c.greet
puts c.is_a?(Animal)
... Meow! Hi, I'm Tom true
Cat never defines greet itself — it comes entirely from the Greetable module, mixed in with include, and it can even call name because that's defined on Animal, which Cat inherits from. super + " Meow!" calls Animal's speak ("...") and appends to it. Cat ends up combining a real superclass (Animal) with an unrelated bundle of mixed-in behavior (Greetable) — composition from two independent sources at once. Next: exceptions — begin/rescue/ensure/raise, Ruby's real structured exception-handling syntax.
Practice exercise
Define module Greetable with a greet method returning "Hi, I'm #{name}". Define class Animal with attr_reader :name and initialize(name). Define class Cat < Animal that includes Greetable. Create a Cat named "Tom" and print its greet, then print whether it is_a?(Animal).