Ruby — classes extending and including modules

In Ruby, modules can be used to encapsulate reusable code that can be included in classes, either as instance methods or class methods. The example below show the difference between the ├Čncludeand extend mechanisms. include mixes in the module methods as instance methods. The extend mechanism imports the module methods as class methods.

module ReusableModule
  def module_method
    puts "Module Method: Hi there!"
  end
end

class ClassThatIncludes
  include ReusableModule
end
class ClassThatExtends
  extend ReusableModule
end

puts "Include"
ClassThatIncludes.new.module_method       # "Module Method: Hi there!"
puts "Extend"
ClassThatExtends.module_method            # "Module Method: Hi there!"

This produces the output

Include
Module Method: Hi there!
Extend
Module Method: Hi there!

So when a class extend a module, the module methods are added to the class as class methods (corresponding to static methods in Java). When a Ruby class include a module, the module methods are added to the class as instance methods.

Leave a comment