在Ruby中,require_relative和require有什么区别?
当前回答
我刚刚看到RSpec的代码中有一些关于require_relative是O(1)常数和require是O(N)线性的注释。因此,可能区别在于require_relative比require更可取。
其他回答
我刚刚看到RSpec的代码中有一些关于require_relative是O(1)常数和require是O(N)线性的注释。因此,可能区别在于require_relative比require更可取。
来自Ruby API:
require_relative complements the builtin method require by allowing you to load a file that is relative to the file containing the require_relative statement. When you use require to load a file, you are usually accessing functionality that has been properly installed, and made accessible, in your system. require does not offer a good solution for loading files within the project’s code. This may be useful during a development phase, for accessing test data, or even for accessing files that are "locked" away inside a project, not intended for outside use. For example, if you have unit test classes in the "test" directory, and data for them under the test "test/data" directory, then you might use a line like this in a test case: require_relative "data/customer_data_1" Since neither "test" nor "test/data" are likely to be in Ruby’s library path (and for good reason), a normal require won’t find them. require_relative is a good solution for this particular problem. You may include or omit the extension (.rb or .so) of the file you are loading. path must respond to to_str.
您可以在http://extensions.rubyforge.org/rdoc/classes/Kernel.html上找到相关文档
我想补充的是,当使用Windows时,你可以使用require './1。如果脚本在本地或映射的网络驱动器上运行,但如果从UNC \\servername\sharename\文件夹路径运行,则需要使用require_relative './1.rb'。
我不参与其他原因的讨论。
上面的答案是正确的,但技术性很强。对于刚接触Ruby的人:
Require_relative很可能用于从您编写的另一个文件引入代码。
例如,如果数据在~/my-project/data中。你想把它包含在~/my-project/solution。Rb ?在解决方案。Rb你会添加require_relative 'data'。
需要注意的是,这些文件不需要在同一个目录中。require_relative“. . / . ./folder1/folder2/data'也是有效的。
Require很可能用于从别人编写的库中引入代码。
例如,如果您想使用active_support库中提供的一个helper函数,该怎么办?你需要用gem install activesupport安装gem,然后在文件中要求'active_support'。
require 'active_support/all'
"FooBar".underscore
说不同,
Require_relative需要一个专门指向调用它的文件的文件。 require要求包含在$LOAD_PATH中的文件。
看看这些文件:
Require_relative是内置方法require的补充,它允许你加载一个相对于包含Require_relative语句的文件的文件。 例如,如果你在"test"目录下有单元测试类,在"test/data"目录下有它们的数据,那么你可以在测试用例中使用这样的行: require_relative“数据/ customer_data_1”
推荐文章
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- 在Gem::Specification.reset期间未解决的规格: