解释ruby中的类时出错

时间:2013-11-13 16:08:31

标签: ruby file require

我正在尝试运行这段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>'

2 个答案:

答案 0 :(得分: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?

答案 1 :(得分:0)

错误消息不仅仅是描述性的。 Ruby根本找不到'restaurant.rb'文件,你正在尝试这个文件。