Extend vs Include in Ruby Module

Extend vs. Include Modules are used for mixins, ruby’s way of handling muliple inheritance without the complications. There are two ways to mixin, either include or extend to mix in a module’s functionality into a class.

Difference:

include makes the module’s methods available to the instance of a class, attached to the instances of the class alone.

1
2
3
4
5
6
7
8
9
10
11
12
module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

extend makes these methods available to the class as class methods, implemented with a self << class*

1
2
3
4
5
6
class Baz
  extend Foo
end

Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #\<Baz:0x1e708>

More information here at the source link.

Any questions on this, please feel free to ask. We’re here to help…

Comments

Comments