What a module is

Free preview 2 min to read

A third keyword, after class and def

The two previous Ruby OOP courses used class/end to build blueprints and def/end to build methods. Ruby has a third container, module/end. It looks almost like a class but does a different job:

module Greetable
  def greeting
    "Hi, I am a #{self.class}"
  end
end

module Greetable ... end defines a named container that holds one method, greeting. Nothing here creates an object, and Greetable itself never will. That's the difference from class this lesson starts with.

A module can't be instantiated

Greetable.class
# => Module, not Class

Greetable.new
# NoMethodError: undefined method 'new' for module Greetable

Greetable.class returns Module, a different built-in class from Class. BankAccount.new worked all through the classes course because BankAccount is a Class, and .new is a method every Class provides. Module doesn't provide .new, so calling it raises NoMethodError.

A module holds methods but has nothing to run them on

Greetable#greeting is an ordinary method, def/end as in earlier courses. It has no object to run on yet. On its own, Greetable is a piece of behavior with no owner: valid Ruby, but not useful by itself. The next two lessons cover the two ways to attach that behavior to a class, include and extend, and each gives a different result.

What this course covers

  1. What a Module Is: module/end, and why a module can't be instantiated (this lesson)
  2. include Adds Instance Methods: mixing a module's methods into every instance of a class
  3. extend Adds Class Methods: mixing a module's methods onto the class itself
  4. include vs extend, Same Module: the same module, both ways, compared side by side
  5. Modules as Namespaces: a second, unrelated job modules do
  6. A Real Mixin: Translatable: this app's own module, used across its models
  7. Putting It Together: combining both mechanisms in one small system

By the end, module, include and extend will be as familiar as class, initialize and <.

Lesson 1 of 7 · free

Keep going with lesson 2

include adds instance methods

Shows how include inserts a module into a class's ancestors so every instance can call its methods.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...