ruby - Ruby 中的 "include module"和 "extend module"有什么区别?

标签 ruby module include extend

<分区>

Possible Duplicate:
What is the difference between include and extend in Ruby?

给定:

module my_module
  def foo
    ...
  end
end

问题一

有什么区别:

class A
  include my_module
end

class A
  extend my_module
end

问题二

foo 视为实例方法还是类方法? 换句话说,这是否等同于:

class A
  def foo
    ...
  end
end

或:

class A
  def self.foo
    ...
  end
end

?

最佳答案

很久以前我写了一篇关于这个的博客文章here .

当您“包含”一个模块时,模块被包含,就好像方法是在包含它们的类中定义的,您可以说它正在将方法复制到包含类。

当您“扩展”一个模块时,您是在说“将这个模块的方法添加到这个特定实例”。当您在类定义中并说“扩展”时,“实例”是类对象本身,但您也可以这样做(如我上面的博文中所示):

module MyModule
  def foo
    puts "foo called"
  end
end

class A
end

object = A.new
object.extend MyModule

object.foo #prints "foo called"    

因此,它不完全是类方法,而是您称为“扩展”的“实例”的方法。当您在类定义中执行此操作并且其中的实例是类本身时,它“看起来像”一个类方法。

关于ruby - Ruby 中的 "include module"和 "extend module"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709618/

相关文章:

ruby-on-rails - Rails4 迁移-添加 null : false to an add_reference method?

ruby - gmail 的 omniauth oauth token 无效

ruby - capybara - 无法点击链接

angular - Angular 中共享模块的理想大小

javascript - node.js 包含类文件

ruby - 匹配 rails 中的数组项

python - 为什么Python不调用模块中的函数?

Angular AppComponent 在子组件之后加载

c++ - 包含 vector 时 Visual Studio 崩溃

php include语句无法打开流到当前目录上方目录中的文件