4.1. Basics of module creation and use

Writing a module is similar to writing a class, except you start your definition with the module keyword instead of the class keyword:

module MyFirstModule
  def say_hello
    puts "Hello"
  end

end

When you write a class, you then create instances of the class. Those instances can execute the class’s instance methods. In contrast, modules don’t have instances. Instead, modules get mixed in to classes, using either the include method or the prepend method.

Note

prepend is new in Ruby 2.0, whereas include has been part of Ruby since the beginning.

A module “mixed in” in this manner is sometimes referred to as a “mix-in.” The result of mixing in a module is that instances of the class have access ...

Get The Well-Grounded Rubyist, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.