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, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.