在Ruby中,require_relative和require有什么区别?
当前回答
绝对路径
require './app/example_file.rb'
缩短的名字
require_relative 'example_file'
其他回答
看看这些文件:
Require_relative是内置方法require的补充,它允许你加载一个相对于包含Require_relative语句的文件的文件。 例如,如果你在"test"目录下有单元测试类,在"test/data"目录下有它们的数据,那么你可以在测试用例中使用这样的行: require_relative“数据/ customer_data_1”
绝对路径
require './app/example_file.rb'
缩短的名字
require_relative 'example_file'
来自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上找到相关文档
总结
使用要求安装宝石
对于本地文件使用require_relative
require使用$LOAD_PATH查找文件。 Require_relative使用语句使用文件的当前位置
需要
Require依赖于你已经安装(例如gem install [package])一个包在你的系统的某个地方的功能。
当使用require时,你可以使用"。/"格式为当前目录下的文件,例如require "。/my_file”,但这不是一个常见的或建议的做法,你应该使用require_relative代替。
require_relative
这仅仅意味着包含“相对于require_relative语句的文件位置”的文件。我通常建议文件应该“在”当前目录树中,而不是“向上”,例如不要使用
require_relative '../../../filename'
(最多3个目录级别),因为这会产生不必要的、脆弱的依赖关系。然而,在某些情况下,如果你已经在目录树中“深入”,那么“上下”另一个目录树分支可能是必要的。也许更简单的是,不要对这个存储库之外的文件使用require_relative(假设你使用的是git,这在2018年底基本上是一个事实上的标准)。
注意,require_relative使用带有require_relative语句的文件的当前目录(所以不一定是您使用命令的当前目录)。这使require_relative路径保持“稳定”,因为它总是相对于以相同方式需要它的文件。
我想补充的是,当使用Windows时,你可以使用require './1。如果脚本在本地或映射的网络驱动器上运行,但如果从UNC \\servername\sharename\文件夹路径运行,则需要使用require_relative './1.rb'。
我不参与其他原因的讨论。
推荐文章
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- 在Gem::Specification.reset期间未解决的规格: