我的问题类似于“Ruby中include和extend的区别是什么?”
Ruby中require和include的区别是什么?如果我只是想在我的类中使用模块中的方法,我应该要求它还是包含它?
我的问题类似于“Ruby中include和extend的区别是什么?”
Ruby中require和include的区别是什么?如果我只是想在我的类中使用模块中的方法,我应该要求它还是包含它?
当前回答
例如:当你使用require 'math'时,你必须写math::PI。 但是当你使用include math时,你可以简单地写成PI。
其他回答
require(name)
它将返回bolean true/false
作为参数传递给require的名称,ruby将尝试在加载路径中找到具有该名称的源文件。 如果你尝试在第一次之后加载相同的库,require方法将返回' false '。require方法仅在您正在加载的库定义在单独的文件中时才需要使用。 所以它会跟踪那个库是否已经被加载。
include module_name
假设你需要在两个不同的类中有一些方法。这样就不需要在两个类中都写了。相反,你可以在module中定义它。然后将此模块包含在其他类中。 它是由Ruby提供的,只是为了保证DRY原则。它用于DRY代码以避免重复
来自编程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()导入库。
'Load'-插入文件内容。(每次调用文件时解析文件)
'Require'-插入一个文件解析的内容。(文件解析一次,存储在内存中)
'Include'-将模块包含到类中,并可以使用模块内的方法作为类的实例方法
'Extend'-将模块包含到类中,并可以使用模块内的方法作为类方法
下面是require和include之间的一些基本区别:
要求:
Require从文件系统读取文件,解析它,保存到内存中,并在给定的位置运行它,这意味着如果你在脚本运行时更改了任何内容,那么这些更改将不会反映出来。 我们按名称要求文件,而不是按模块名。 它通常用于库和扩展。
包括:
当你将一个模块包含到你的类中时,它的行为就像你将模块中定义的代码插入到你的类中一样。 我们包含模块名,而不是文件名。 它通常用于干涸代码和删除代码中的重复。