Modules and Mixins

As we saw in Mixins, when you include a module into a Ruby class, the instance methods in that module become available as instance methods of the class, like this:

 module​ ​Logger
 def​ ​log​(msg)
  STDERR.​puts​ Time.​now​.​strftime​(​"%H:%M:%S: "​) + ​"​​#{​self​}​​ (​​#{​msg​}​​)"
 end
 end
 
 class​ Song
 include​ Logger
 end
 
 s = Song.​new
 s.​log​(​"created"​)

Produces:

 17:16:19: #<Song:0x0000000104717708> (created)

Ruby implements include very simply. The module you include is added as an ancestor of the class being defined. It’s as if the module is the parent of the class that it’s mixed into. And that would be the end of the description except for one small wrinkle. Because the module is injected ...

Get Programming Ruby 3.3 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.