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

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


当前回答

在Ruby元编程书中,

require()方法非常类似于load(),但它的目的是 不同的目的。您使用load()来执行代码,并且使用 Require()导入库。

其他回答

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

MyModule = Module.new
require MyModule # see what happens

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

What's the difference between "include" and "require" in Ruby? Answer: The include and require methods do very different things. The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method. The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

所以如果你只是想使用一个模块,而不是扩展它或做一个混合,那么你会想要使用require。

奇怪的是,Ruby的require类似于C的include,而Ruby的include几乎与C的include完全不同。

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

来自编程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.

在Ruby元编程书中,

require()方法非常类似于load(),但它的目的是 不同的目的。您使用load()来执行代码,并且使用 Require()导入库。