本文介绍了加载在本地路径上工作,不需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

loadee.rb

loadee.rb

puts '> This is the second file.'

loaddemo.rb

loaddemo.rb

puts 'This is the first (master) program file.'
load 'loadee.rb'
puts 'And back again to the first file.'

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

When I run "ruby loaddemo.rb", This works fine. Both files are in the same directory, and that's the directory I run from.

但是,如果我将负载更改为require,无论是否带有扩展名,我都会得到:

But if I change the load to a require, and with or without the extension I get:

<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>'

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

My question is of course, why isn't require working in this case? It should, right? Do load and require use different paths?

Ruby版本1.9.2

Ruby version 1.9.2

推荐答案

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

If you provide just a filename to require, it will only look in the predefined $LOAD_PATH directories. However, if you provide a path with your filename, it should work:

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

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

You could also add your project's folder to the load path instead:

$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.'

这篇关于加载在本地路径上工作,不需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:43