Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

Contrary to the currently accepted answer, the argument 'second.rb' does not resolve to an absolute path. If that were what was meant, you would also be able to require 'second.rb', since require has exactly the same wording about absolute paths.

I think what's happening here is just that the phrasing in the documentation for load is not clear at all about what the actual steps are. When it says "Loads and executes the Ruby program in the file filename," it means that literally — it treats the argument as a file name and attempts to load it as a Ruby program. If isn't an absolute path†, then Ruby goes through $LOAD_PATH and looks for it in those places. If that doesn't turn anything up, then it just goes ahead and tries to open it just as you passed it in. That's the logic that MRI actually follows.

† The actual check that Ruby does is essentially "Does the path start with '/', '~' or './'?".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top