Search code examples
rubymixins

How to tell if a method in a module is instance method or class method


I understand that include creates instance methods and extend creates class methods. How do we tell whether a method is instance or class method?

In the following example, it looks like a method is an instance method and a class method. Is there no difference between instance and class methods in some cases?

module Test
  def aux
    puts 'aux'
  end
end

class A
  include Test
end

class B
  extend Test
end

a = A.new
a.aux
B.aux

Solution

  • The difference between include and extend is how the class that is mixing the module will behave. Both include and extend will only work on a module's 'instance' methods (that is, methods that don't start with ModuleName or self)

    Example:

    module Foo
      def a
        puts "a"
      end
    
      def Foo.b
        puts "b"
      end
    
      def self.c
        puts "c"
      end
    end
    

    a class that includes this module will only have access to a as an instance method while a class that extends it while only have access to a as a class method. Neither will have access to b or c as those are Foo's class methods and can only be accessed by calling Foo.b or Foo.c