11

I have a folder full of ruby files, and when I try and require one file in another that is in the same directory using require 'file' I get a LoadError but when I use require './file' everything works fine. Can somebody explain to me why this happens and if there is any way I can require a file without adding a ./ onto the file?

(Picture of directory): alt text

Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
ab217
  • 16,358
  • 25
  • 69
  • 90

3 Answers3

15

If you want to require a file not from the system $LOAD_PATH but rather relative to the directory of the file you are requireing from, you should use require_relative. (Which, as you can see, isn't exactly extensively documented.)

Jörg W Mittag
  • 351,196
  • 74
  • 424
  • 630
3

You don't have current directory in your loadpath.

Check the contents of the $LOAD_PATH variable

glebm
  • 18,903
  • 8
  • 49
  • 67
0

Though it is very old post I think some extra information will be very useful to beginner.

The best way to think of require is in relation to the UNIX $PATH variable. Just by way of a refresher, the $PATH variable in UNIX is a list of directories where executables can be found. So when you type the name of a program on any UNIX terminal, your computer is looking through the executable files in the directories specified in your $PATH variable. require does something very similar. When, for example, you write require 'set' at the top of your Ruby file, you are telling Ruby to look through a bunch of directories for a library called set.rb (Ruby's set library).

So where does Ruby look for set.rb? Well, once again, Ruby has something very similar to UNIX's $PATH variable. It is the global variable $LOAD_PATH also sometimes known by it's ugly and undescriptive alias $: (which I don't suggest using by the way--short though it may be). It is an array of directory names where Ruby looks when it comes across a require.

There is nice informative post here where you can get more information about require, load and require_relative

Engr. Hasanuzzaman Sumon
  • 2,003
  • 3
  • 28
  • 38