如何要求另一个目录中的ruby文件 [英] How to require a ruby file from another directory

查看:94
本文介绍了如何要求另一个目录中的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:

  • $LOAD_PATH
  • require
  • require_relative
  • File.dirname
  • __FILE__

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

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