What is the differnece betwee...
What is the differnece betwee...
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:
module A
def hello
"world"
end
end
class Foo
include A
end
Foo.new.hello # => "world"
Foo.hello # => NoMethodError
On the other hand, the extend
keyword is used to add methods from a module to a class as class methods. When a class extends a module, the methods are added to the singleton class of the class. This means that the methods can be called directly on the class itself, but not on its instances.
For instance, using the same module A
, if a clas...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào