Thuta Learning
AdvancedProgrammingbeginner

Modules & Mixins

Relax. We'll talk through this in plain words — no textbook voice.

Module is a container that bundles together methods and constants. Ruby uses modules both for namespacing and as mixins you can bring into a class.

ruby
module Drivable
  def drive
    puts "Vroom vroom!"
  end
end

class Car
  include Drivable
end

class Truck
  include Drivable
end

Car.new.drive
Truck.new.drive

include Drivable lets a class use the module's drive method. This is handy when you want to share behavior without using inheritance.

You should see
Vroom vroom! Vroom vroom!

Info

Module names should also start with a capital letter, just like class names.

Easy traps

  • You can't instantiate a module like an object with Drivable.new — a module isn't a class.