【问题标题】:Error while interpreting a class in ruby在 ruby​​ 中解释类时出错
【发布时间】:2013-11-13 16:08:30
【问题描述】:

我正在尝试运行这段 Ruby 代码,但出现错误,这似乎是什么问题?

require 'restaurant'

class Guide
  def initialize(path=nil)
    #locate the restaurant text file at path
    Restaurant.filepath=path
    if Restaurant.file_exists
      puts "Found restaurant file"
      #or create a new file
    elsif Restaurant.create_file
      puts "Created restaurant file"
      #exit if create fails
    else 
      puts "\n\nExiting\n\n"
      exit!
    end
  end
end

这是我得到的错误:

/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- restaurant (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from guide.rb:1:in `<main>'

【问题讨论】:

  • 请缩进你的代码!这对我们也没有帮助,但您在以后阅读自己的代码时也会受益于正确的格式。

标签: ruby file require


【解决方案1】:

当您需要来自 ruby​​ 的文件时,它会在全局变量 $LOAD_PATH(也缩写为 $:)的所有目录中查找该文件。这通常包含当前目录(称为./),因此您需要明确告诉Ruby 去那里查看:

require './restaurant'

另一种选择是使用require_relative

require_relative 'restaurant'

如果您愿意,也可以将当前目录附加到$LOAD_PATH

$: << File.expand_path(__FILE__)
require 'restaurant'

附带说明,在 Ruby 1.9.2 之前,当前目录实际上位于 $LOAD_PATH,另请参阅 Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative?

【讨论】:

    【解决方案2】:

    这里的错误消息不仅仅是描述性的。 Ruby 根本找不到您试图要求的“restaurant.rb”文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2013-03-10
      相关资源
      最近更新 更多