简体   繁体   中英

How does Ruby's $LOAD_PATH get affected in other files when changed in one file?

I have the following project directory structure:

.
├── bin
├── lib
│   ├── foo
│   │   ├── bar.rb
│   │   └── baz.rb
│   └── foo.rb
└── test

foo.rb :

require 'foo/bar'

bar.rb :

require 'foo/baz'

baz.rb :

puts "baz"

When I run foo.rb by adding the lib directory to the load path, Ruby prints out:

"baz"

I added the lib directory to the load path in foo.rb . How does it get added to load path in foo/bar.rb as well?

$LOAD_PATH is a global variable shared between all files in a single ruby process. So when one file modifies it, any code executed after the modification will also use the modified version.

You can read more about global variables here

as other pointed out already LOAD_PATH is global. You should not be relying on tricks like this though. In your case the right thing to do is to use require_relative

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM