What is the differnece between extend and include in ruby?
What is the differnece between extend and include in ruby?
In Ruby, the keywords include and extend are both used to mix modules into classes, but they serve different purposes and affect the scope of method accessibility in distinct ways.
The include keyword is used to add the methods from a module into a class as instance methods. This means that the methods defined in the module become part of the instances of the class. When a class includes a module, Ruby places the module in the ancestor chain of the class. This is why methods defined in the module can be called on instances of the class, but not directly on the class itself.
For example, if you have a module A with a method hello and a class Foo that includes A, you can call hello on an instance of Foo but not on Foo itself:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.