在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”
来自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 './app/example_file.rb'
缩短的名字
require_relative 'example_file'
我刚刚看到RSpec的代码中有一些关于require_relative是O(1)常数和require是O(N)线性的注释。因此,可能区别在于require_relative比require更可取。
上面的答案是正确的,但技术性很强。对于刚接触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中的文件。
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 如何测试参数是否存在在轨道
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法