Ruby: modules extending/including modules

I mix its bag of tricks into B

This phrase and your question in general made me believe there is a little misunderstanding in concept of include/extend thing. I apologize in advance, because I don't fully understand the question.

For example you have such module:

module A
  def a
    puts "a"
  end

  def self.b
    puts "b"
  end
end

As you see there are 2 types of methods:

  • singleton_methods
  • instance_methods

Here is the easiest way to show that they actually differ:

A.singleton_methods
=> [:b]
A.instance_methods
=> [:a]
A.a
NoMethodError: undefined method `a' for A:Module
A.b
b
=> nil

If you do include A simplistically you are adding its instance methods to the current module instance methods. When you do extend A simplistically you are adding its instance methods to the current module singleton methods.

module B
  include A
end

module C
  extend A
end

B.instance_methods
=> [:a]
B.singleton_methods
=> []
C.instance_methods
=> []
C.singleton_methods
=> [:a]

One more thing to say is that you could extend self but not include self as that doesn't make any sense and also will raise an exception.

module D
  extend self

  def a
    puts "a"
  end

  def self.b
    puts "b"
  end
end

D.singleton_methods
=> [:b, :a]
D.instance_methods
=> [:a]
D.a
a #no error there because we have such singleton method
=> nil

I guess these things could help you. There are a lot of questions about extend/include on StackOverflow you may check (example).