【问题标题】:load works on local path, require doesn'tload 在本地路径上工作,require 不
【发布时间】:2011-08-25 07:54:45
【问题描述】:

loadee.rb

puts '> This is the second file.'

loaddemo.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

【问题讨论】:

    标签: ruby ruby-1.9.2


    【解决方案1】:

    如果您只为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​​ 的错误。 1.9 在使用require 时从加载路径中删除了“当前目录”,但对于load 则没有。 redmine.ruby-lang.org/issues/2710
    • 另外,请记住,每次使用 load 时,它都会评估整个文件,而使用 require 只会在您第一次需要时评估文件。
    【解决方案2】:

    提供带有文件名的路径似乎不适合我,我不想将一堆路径塞进我的$LOAD_PATH

    查看documentation,我找到了require_relative

    require_relative 'loadee'
    

    适用于1.9.22.1.2

    documentation 表示require 根本不打算搜索相对路径,load 也不是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2022-11-18
      • 2013-05-21
      • 2019-07-01
      • 1970-01-01
      相关资源
      最近更新 更多