1

I am trying to run this piece of Ruby code but getting an error , what seems to be the problem ?

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

this is the error I get:

/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>'
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
EA Rashel
  • 167
  • 2
  • 9
  • 1
    Please indent your code! This will not also help us but you will also benefit from proper formatting when reading your own code later. – Patrick Oscity Nov 13 '13 at 16:27

2 Answers2

1

When you require a file from ruby, it looks for this file in all directories of the global variable $LOAD_PATH (also abbreviated with $:). This does typically not include the current directory (referred to as ./), so you need to tell Ruby explicitly to look there:

require './restaurant'

Another option is to use require_relative:

require_relative 'restaurant'

If you like you can also append your current directory to $LOAD_PATH.

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

As a side note, before Ruby 1.9.2 the current directory was actually in $LOAD_PATH, also see Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative?

Community
  • 1
  • 1
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
0

The error message is more than descriptive here. Ruby simply cannot find 'restaurant.rb' file, which you're trying to require.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91