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


Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now