Câu hỏi phỏng vấn Ruby
Câu hỏi

What is the differnece betwee...

Câu trả lời

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.

Include

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

Extend

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

expert

Gợi ý câu hỏi phỏng vấn

junior

Which of the expressions listed below will result in "false"?

middle

What is the difference between Kernel#require and Kernel#load ?

entry

What is an object in ruby?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào