Include vs Prepend in Ruby

Include

The example below has a class Foo with instance method, meth. The module has the method with the same name. Let's include the Mojule, in the Foo class as shown below:

class Foo
  def meth
    puts "Foo#meth called"
  end
end

module Mojule
  def meth
    super
    puts "Exiting meth in Mojule"
  end
end

class Foo
  include Mojule
end

Foo.new.meth

This prints:

Foo#meth called

The hierarchy can be printed:

p Foo.ancestors

This prints:

[Foo, Mojule, Object, Kernel, BasicObject]

Mojule is the parent of Foo.

Prepend

The prepend example is as below:

class Foo
  def meth
    puts "Foo#meth called"
  end
end

module Mojule
  def meth
    super
    puts "Exiting meth in Mojule"
  end
end

class Foo
  prepend Mojule
end

Foo.new.meth

This prints:

Foo#meth called
Exiting meth in Mojule

If you print the hierarchy:

p Foo.ancestors
[Mojule, Foo, Object, Kernel, BasicObject]

You can see that the Mojule is the child of Foo.

Conclusion

The include makes the included module to be above the class where it is included. The prepend makes the prepended module to be below the class where it is prepended.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.