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:
|
|
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:
|
|
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方法可以將模組的方法添加到類的實例方法中,即被添加的模組的方法可以被該類的實例調用。
例如:
|
|
上述代碼中,MyClass類包含一個MyModule模組,並且MyModule模組中的方法可以被MyClass類的實例方法(即obj.my_method)調用。
extend方法可以將模組的方法添加到類的類方法中,即被添加的模組的方法可以直接被該類調用,而不需要實例化對象。
|
|
上述代碼中,MyClass類擴展了MyModule模組,並且MyModule模組中的方法可以直接被MyClass類的類方法(即MyClass.my_method)調用,而不需要實例化對象。
簡單來說,include方法用於將模組的方法添加到類的實例方法中,而extend方法用於將模組的方法添加到類的類方法中。