加载器.rb
puts '> This is the second file.'
加载演示.rb
puts 'This is the first (master) program file.'
load 'loadee.rb'
puts 'And back again to the first file.'
当我运行 "ruby loaddemo.rb"
时,效果很好。这两个文件都在同一个目录中,这就是我运行的目录。
但是,如果我将负载更改为要求,无论有无扩展名,我都会得到:
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load
-- loadee.rb (LoadError)
from <internal:lib/rubygems/custom_require>:29:in `require'
from loaddemo.rb:2:in `<main>'
我的问题当然是,为什么在这种情况下不需要工作?应该的吧? load 和 require 是否使用不同的路径?
ruby 版本 1.9.2
最佳答案
如果您只为 require
提供文件名,它只会在预定义的 $LOAD_PATH
目录中查找。但是,如果您提供带有文件名的路径,它应该可以工作:
puts 'This is the first (master) program file.'
require './loadee.rb'
puts 'And back again to the first file.'
您也可以将项目的文件夹添加到加载路径:
$LOAD_PATH.unshift File.dirname(__FILE__)
puts 'This is the first (master) program file.'
require 'loadee.rb'
puts 'And back again to the first file.'
最后,您可以只使用 require_relative
代替:
puts 'This is the first (master) program file.'
require_relative 'loadee.rb'
puts 'And back again to the first file.'
关于ruby - load 在本地路径上工作,require 不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5998917/