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)
提供带有文件名的路径似乎对我不起作用,我不想把一堆路径塞进我的$LOAD_PATH.
检查文档,我发现require_relative.
require_relative 'loadee'
Run Code Online (Sandbox Code Playgroud)
适用于1.9.2和2.1.2.
的文档表示require不意图在所有搜索相对路径,也不是load.
| 归档时间: |
|
| 查看次数: |
21077 次 |
| 最近记录: |