January 2024
Intermediate to advanced
718 pages
20h 15m
English
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 ...
Read now
Unlock full access