什么标准证明在Ruby中使用模块而不是类?

Mun*_*lam 6 ruby

我正在读我的红宝石书.看下面的代码,

module Destroy
  def destroy(anyObject)
    @anyObject = anyObject
    puts "I will destroy the object: #{anyObject}"
  end
end

class User
  include Destroy
  attr_accessor :name, :email
  def initialize(name,email)
    @name  = name
    @email = email
  end
end

my_info = User.new("Bob","Bob@example.com")
puts "So your name is: #{my_info.name} and you have email #{my_info.email}"

user = User.new("john","john@example.com")
user.destroy("blah")
Run Code Online (Sandbox Code Playgroud)

我可以在我的课堂上创建另一种方法.我为什么要这样做?我为什么要使用模块?将其嵌入到其他类中并不比仅使用普通继承更容易.

Dom*_*Dom 3

您可以将模块及其内部的方法和常量视为更多地提供实用函数和操作,您可以根据需要将它们包含到其他对象中。例如,如果您想在对象中使用 destroy 函数FooBar您将执行类似的操作:

\n\n
class Foo\n  include Destroy\n  # other code below\nend\n\nclass Bar\n  include Destroy\n  # other code below\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在任何Foo对象Bar都可以访问 destroy 内部的所有方法或常量。

\n\n

模块定义了一个命名空间,一个沙箱,您的方法和常量可以在其中运行,而不必担心被其他方法和常量踩到。ruby 文档对此进行了更深入的探讨,并包含一个很好的实用示例,说明您何时想要使用它,如下所示:

\n\n
module Debug\n  def whoAmI?\n    "#{self.type.name} (\\##{self.id}): #{self.to_s}"\n  end\nend\nclass Phonograph\n  include Debug\n  # ...\nend\nclass EightTrack\n  include Debug\n  # ...\nend\nph = Phonograph.new("West End Blues")\net = EightTrack.new("Surrealistic Pillow")\nph.whoAmI?  \xc2\xbb   "Phonograph (#537766170): West End Blues"\net.whoAmI?  \xc2\xbb   "EightTrack (#537765860): Surrealistic Pillow"\n
Run Code Online (Sandbox Code Playgroud)\n\n

在此示例中,包含 Debug 的每个类都可以访问 Debug 包含的方法whoAmI?以及其他方法和常量,而无需为每个类重新定义它。

\n