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
  • 78,473
  • 57
  • 200
  • 338
ab217
  • 16,900
  • 25
  • 74
  • 92
  • possible duplicate of [What is the difference between require\_relative and require in Ruby?](http://stackoverflow.com/questions/3672586/what-is-the-difference-between-require-relative-and-require-in-ruby) – Ciro Santilli OurBigBook.com Nov 14 '14 at 17:22

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
  • 363,080
  • 75
  • 446
  • 653
3

You don't have current directory in your loadpath.

Check the contents of the $LOAD_PATH variable

glebm
  • 20,282
  • 8
  • 51
  • 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,103
  • 3
  • 29
  • 38