Search code examples
rubyload-path

Why load "file.rb" works even though "." is not in the load path?


I have created a project in /Projects/test that have the following files:

/Projects/test/first.rb
/Projects/test/second.rb

In first.rb, I do:

load 'second.rb'

And it gets loaded correctly. However, if I open the console and I type $:, I don't see the current directory "." in the load path. How does Ruby know where to load that 'second.rb' from?


Solution

  • See the documentation of Kernel#load clearly :

    Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program’s global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

    In case load 'second.rb' - second.rb has been internally resolved to the absolute path /Projects/test/second.rb,as your requiring file in the directory is same as required file directory. Nothing has been searched to the directories listed in$: for your case.

    Just remember another way always - The load method looks first in the current directory for files