Include vs Extend

Include vs Extend

In Ruby, include and extend are both methods used to add module methods to a class.

The include method adds the module’s methods to the instance methods of a class, meaning the methods from the included module can be called by instances of the class.

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
module HiModule
  def hi_method
    puts "Hi, this is my method!"
  end
end

class HiClass
  include HiModule
end

obj = HiClass.new
obj.hi_method # => Hi, this is my method!

In the above code, the MyClass class includes a MyModule module, and the methods from MyModule module can be called by instance methods of MyClass class (i.e., obj.my_method).

On the other hand, the extend method adds the module’s methods to the class methods of a class, meaning the methods from the extended module can be called directly by the class itself, without instantiating any objects.

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
module HiModule
  def hi_method
    puts "Hi, this is my method!"
  end
end

class HiClass
  extend HiModule
end

HiClass.hi_method # => Hi, this is my method!

In the above code, the MyClass class extends the MyModule module, and the methods from MyModule module can be called directly by class methods of MyClass class (i.e., MyClass.my_method).

In summary, the include method is used to add module methods to a class’s instance methods, while the extend method is used to add module methods to a class’s class methods.

Include vs Extend

在Ruby中,include和extend都是用來將模組(module)的方法添加到類(class)中的方法。

include方法可以將模組的方法添加到類的實例方法中,即被添加的模組的方法可以被該類的實例調用。

例如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
module HiModule
  def hi_method
    puts "Hi, this is my method!"
  end
end

class HiClass
  include HiModule
end

obj = HiClass.new
obj.hi_method # => Hi, this is my method!

上述代碼中,MyClass類包含一個MyModule模組,並且MyModule模組中的方法可以被MyClass類的實例方法(即obj.my_method)調用。

extend方法可以將模組的方法添加到類的類方法中,即被添加的模組的方法可以直接被該類調用,而不需要實例化對象。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
module HiModule
  def hi_method
    puts "Hi, this is my method!"
  end
end

class HiClass
  extend HiModule
end

HiClass.hi_method # => Hi, this is my method!

上述代碼中,MyClass類擴展了MyModule模組,並且MyModule模組中的方法可以直接被MyClass類的類方法(即MyClass.my_method)調用,而不需要實例化對象。

簡單來說,include方法用於將模組的方法添加到類的實例方法中,而extend方法用於將模組的方法添加到類的類方法中。

updatedupdated2023-03-022023-03-02