What a module is
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
- What a Module Is:
module/end, and why a module can't be instantiated (this lesson) - include Adds Instance Methods: mixing a module's methods into every instance of a class
- extend Adds Class Methods: mixing a module's methods onto the class itself
- include vs extend, Same Module: the same module, both ways, compared side by side
- Modules as Namespaces: a second, unrelated job modules do
- A Real Mixin: Translatable: this app's own module, used across its models
- 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 <.
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.