Modules in Ruby

A deeper dive than usual

Hal Fulton


June 3, 2019

I wrote one of these books

A module is...

  • A tool for namespacing
  • A container for methods and constants
  • Like a class, but not

A module is
not a class...

  • Can't be instantiated
  • Has no

  • Has no instance variables (of its own)

initialize

What can we do

with a module?

  • "nothing" (namespacing)
  • include
  • extend
  • prepend

Namespacing

  • Math::PI
  • Math::sin
  • Math.sin
  • ThisClass::SomeModule
  • ThisModule::OtherClass
  • A::B:C::D::Constant
  • A::B::C::D::method
  • A::B::C::D.method

"Partial" Multiple Inheritance?

class Asian
end

module Mormon
end

class RubyInventor < Asian
  include Mormon
end

p RubyInventor.ancestors   
# [RubyInventor, Mormon, Asian, Object, Kernel, BasicObject]

matz = RubyInventor.new
p matz.is_a? Asian          # true
p matz.is_a? Mormon         # true

Some core modules

  • Comparable           <=>
    
  • Enumerable           each
     

                          depends on         
  being implemented

depends on 

  • Forwardable
  • Math
include
extend
prepend

Manipulating Modules

Copy all constants/methods into a context
(methods go to "current" level)

Copy all constants/methods (methods go in as singletons) -- most commonly used to create class methods

Copy all constants/methods -- methods are given *precedence* over the class's own instance methods!

The Superman example...

ancestors

Idea: Pluggable implementations

I hope this all makes perfect sense.

Questions?

M

By hal_9000

M

  • 177