Skip to content
Justice Tech School

Modules and Mixins

A module groups methods and constants. include adds instance methods, extend adds class methods and a module can also act as a namespace.

Example
module Walkable; def walk = "#{name} walks"; end
module Swimmable; def swim = "#{name} swims"; end
class Duck
  include Walkable, Swimmable
  attr_reader :name
  def initialize(n) = @name = n
end
d = Duck.new("Don")
puts d.walk, d.swim
puts Duck.ancestors.first(3).inspect

Result

Don walks
Don swims
[Duck, Walkable, Swimmable]

Exercise

Add instance methods from a module.

 Walkable

Quiz Test

What is a mixin?

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