我的问题类似于“Ruby中include和extend的区别是什么?”

Ruby中require和include的区别是什么?如果我只是想在我的类中使用模块中的方法,我应该要求它还是包含它?


当前回答

例如:当你使用require 'math'时,你必须写math::PI。 但是当你使用include math时,你可以简单地写成PI。

其他回答

您曾经尝试过要求一个模块吗?结果如何?试试:

MyModule = Module.new
require MyModule # see what happens

模块不是必需的,只是包含的!

Ruby的require更像其他语言(比如C语言)中的“include”。它告诉Ruby你想引入另一个文件的内容。在其他语言中类似的机制有: 在c#中使用<namespace>指令。 在Java中导入<package>。 Ruby include是用于mixin的面向对象继承机制。

这里有一个很好的解释:

简单的答案是require和include本质上是不相关的。 “require”类似于C中的include,这可能会让新手感到困惑。 (一个显著的区别是所需文件中的局部变量“蒸发”了 当require完成时。) Ruby包含与C包含完全不同。include语句将一个模块“混合”到一个类中。这是有限形式 多重继承。一个被包含的模块字面上赋予了一个“is-a” 对事物的关系包括它。

重点补充道。

来自编程Ruby 1.9

We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.

包括 如下所示,当你将一个模块包含到你的类中时,就好像你将模块中定义的代码插入到类中,在那里你“包含”了它。它允许' mixin '行为。它用于DRY代码以避免重复,例如,如果模块中有多个类需要相同的代码。

负载 load方法几乎类似于require方法,除了它不跟踪库是否已加载。因此,可以多次加载一个库,而且在使用load方法时,必须指定“。Rb:库文件名的扩展名。

需要 require方法允许您加载一个库,并防止它被多次加载。如果你尝试在第一次之后加载相同的库,require方法将返回' false '。require方法只需要在你正在加载的库定义在一个单独的文件中,这是通常的情况。

你可以选择这个 http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/

'Load'-插入文件内容。(每次调用文件时解析文件)

'Require'-插入一个文件解析的内容。(文件解析一次,存储在内存中)

'Include'-将模块包含到类中,并可以使用模块内的方法作为类的实例方法

'Extend'-将模块包含到类中,并可以使用模块内的方法作为类方法