如何从另一个目录中获取 ruby​​ 文件 [英] How to require a ruby file from another directory

查看:37
本文介绍了如何从另一个目录中获取 ruby​​ 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图需要一个我在另一个文件中创建的 rake 文件.这两个文件位于两个不同的目录中.我在第一个文件的顶部有 require ,在 require 之后的引号内有第二个文件的名称.它告诉我它无法加载这样的文件.这是否意味着因为它在不同的目录中找不到它?我尝试坚持第二个文件的完整路径,但它仍然无法加载该文件.有谁知道如何将第二个文件加载到第一个文件中?

I am trying to require a rake file that I have created inside another file I have. These two files are inside two different directories. I have require at the top of my first file with the name of the second file inside the quotes after the require. It is telling me that it can't load such file. Does that mean because its in different directory it can't find it? I tried sticking in the full path to the second file but it still can't load the file. Does anyone know how I can load the second file into the first?

提前致谢

推荐答案

require 将仅在称为加载路径"的一组位置中搜索文件.您可以在脚本或 irb 会话中使用全局变量 $LOAD_PATH 查看加载路径.如果它不在加载路径中,它就不会找到它.

require will search for files in only a set of locations referred to as the "Load Path." You can view the load path by using the global variable $LOAD_PATH in a script or irb session. If it is not in the load path, it won't find it.

Ruby 1.9 引入了 require_relative,它使用当前文件的位置作为起点进行搜索.

Ruby 1.9 introduced require_relative which searches using the current file's location as a starting point.

# Will search $LOAD_PATH for file. 
require 'test/unit'
# Notice the '/' which tells it to look in the 
# 'test' folder for a file named 'unit.rb'

# Will look in current folder of file
require_relative 'my_folder/my_file'
# Will search in 'my_folder' for the file 'my_file.rb'

请注意,require_relative 在 irb 中不起作用.

Note that require_relative will not work in irb.

另请注意,如果您真的想使用 require,您可以通过向 $LOAD_PATH 变量添加一个位置来启动您的脚本.

Also note, that if you really want to use require, you can start your script by adding a location to the $LOAD_PATH variable.

$LOAD_PATH << File.join('users', 'yourusername', 'your_folder')
# or
$LOAD_PATH << File.dirname(__FILE__)
# The second one enables you to move the file around on your
# system and still operate correctly
require 'my_file'

以下是来自 Ruby-Doc 的一些附加文档:

Here's some additional documentation from Ruby-Doc:

这篇关于如何从另一个目录中获取 ruby​​ 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆