ruby include/extend 区别

做为mixins的工具,ruby 里这2个有什么区别

在 Ruby 中,includeextend 都用于将模块的功能混入到类或对象中,但它们的行为方式和影响范围不同。这里是它们之间的主要区别:

1. include:混入实例方法

  • include 将模块中的方法作为实例方法添加到类中。
  • 当你在一个类中 include 一个模块时,这个模块中的方法会成为该类的实例方法,也就是只有通过类的实例才能调用这些方法。

示例:

module Greetings
  def say_hello
    "Hello!"
  end
end

class Person
  include Greetings
end

p = Person.new
puts p.say_hello  # 输出 "Hello!"

在这里,Person 类包含了 Greetings 模块,say_hello 方法成为 Person 类的实例方法,因此可以通过 Person 的实例 p 调用该方法。

2. extend:混入类方法

  • extend 将模块中的方法作为类方法添加到类或对象中。
  • 当你在一个类中 extend 一个模块时,这个模块中的方法会成为该类的类方法,也就是通过类本身(而不是实例)调用这些方法。

示例:

module Greetings
  def say_hello
    "Hello!"
  end
end

class Person
  extend Greetings
end

puts Person.say_hello  # 输出 "Hello!"

在这里,Person 类扩展了 Greetings 模块,say_hello 方法成为 Person 类的类方法,因此可以直接通过 Person 调用。

3. 针对单个对象的 extend

extend 还可以用来为某个对象单独添加模块的方法。

示例:

module Greetings
  def say_hello
    "Hello!"
  end
end

p = Object.new
p.extend(Greetings)

puts p.say_hello  # 输出 "Hello!"

在这个例子中,Greetings 模块的方法被扩展到了 p 这个单独的对象,因此 p 可以调用 say_hello 方法。

总结:

  • include:将模块中的方法作为实例方法引入类中。
  • extend:将模块中的方法作为类方法引入类中,或扩展到特定的对象。