Search code examples
rubymoduleincludeextend

What is the difference between include and extend in Ruby?


Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me.

  • include: mixes in specified module methods as instance methods in the target class
  • extend: mixes in specified module methods as class methods in the target class

So is the major difference just this or is a bigger dragon lurking? e.g.

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!"

Solution

  • What you have said is correct. However, there is more to it than that.

    If you have a class Klazz and module Mod, including Mod in Klazz gives instances of Klazz access to Mod's methods. Or you can extend Klazz with Mod giving the class Klazz access to Mod's methods. But you can also extend an arbitrary object with o.extend Mod. In this case the individual object gets Mod's methods even though all other objects with the same class as o do not.