load在本地路径上工作,require则不工作

Ben*_*ley 22 ruby ruby-1.9.2

loadee.rb

puts '> This is the second file.'
Run Code Online (Sandbox Code Playgroud)

loaddemo.rb

puts 'This is the first (master) program file.'
load 'loadee.rb'
puts 'And back again to the first file.'
Run Code Online (Sandbox Code Playgroud)

当我跑"ruby loaddemo.rb",这工作正常.这两个文件都在同一个目录中,这就是我运行的目录.

但是,如果我将负载更改为require,并且有或没有扩展我得到:

<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>'
Run Code Online (Sandbox Code Playgroud)

我的问题当然是,为什么在这种情况下不需要工作?它应该,对吗?加载并要求使用不同的路径?

Ruby版本1.9.2

Dyl*_*kow 39

如果只提供文件名require,则只会查看预定义的$LOAD_PATH目录.但是,如果您提供带有文件名的路径,它应该可以工作:

puts 'This is the first (master) program file.'
require './loadee.rb'
puts 'And back again to the first file.'
Run Code Online (Sandbox Code Playgroud)

您也可以将项目的文件夹添加到加载路径:

$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.'
Run Code Online (Sandbox Code Playgroud)

最后,你可以require_relative改用:

puts 'This is the first (master) program file.'
require_relative 'loadee.rb'
puts 'And back again to the first file.'
Run Code Online (Sandbox Code Playgroud)

  • 那么为什么加载工作没有路径?它是否使用不同的路径变量? (2认同)
  • 另外,请记住,每次使用`load`时,它都会评估整个文件,而使用`require`只会在第一次需要时评估文件. (2认同)

Kee*_*een 5

提供带有文件名的路径似乎对我不起作用,我不想把一堆路径塞进我的$LOAD_PATH.

检查文档,我发现require_relative.

require_relative 'loadee'
Run Code Online (Sandbox Code Playgroud)

适用于1.9.22.1.2.

文档表示require不意图在所有搜索相对路径,也不是load.