推荐答案
在 Ruby 中,include 和 extend 都用于将模块中的方法引入到类或对象中,但它们的作用范围不同:
include:将模块中的方法作为实例方法引入到类中。extend:将模块中的方法作为类方法引入到类中。
本题详细解读
include 的使用
include 用于将模块中的方法作为实例方法引入到类中。这意味着,当你使用 include 时,模块中的方法将成为类的实例方法,只能通过类的实例来调用。
// www.javascriptcn.com code example
module Greeting
def say_hello
puts "Hello!"
end
end
class Person
include Greeting
end
person = Person.new
person.say_hello # 输出: Hello!在上面的例子中,Greeting 模块中的 say_hello 方法被 include 到 Person 类中,因此可以通过 Person 的实例 person 来调用 say_hello 方法。
extend 的使用
extend 用于将模块中的方法作为类方法引入到类中。这意味着,当你使用 extend 时,模块中的方法将成为类的类方法,可以直接通过类本身来调用。
// www.javascriptcn.com code example
module Greeting
def say_hello
puts "Hello!"
end
end
class Person
extend Greeting
end
Person.say_hello # 输出: Hello!在这个例子中,Greeting 模块中的 say_hello 方法被 extend 到 Person 类中,因此可以直接通过 Person 类来调用 say_hello 方法。
include 和 extend 的区别总结
include:将模块中的方法作为实例方法引入到类中,只能通过类的实例来调用。extend:将模块中的方法作为类方法引入到类中,可以直接通过类本身来调用。
这两种方式的选择取决于你希望模块中的方法在类中如何被使用。如果你希望方法是实例方法,使用 include;如果你希望方法是类方法,使用 extend。