Ruby require

Got a Question to $LOAD_PATH.

When using require ‘mygem’ in the ruby documentation is written:

“If the filename does not resolve to an absolute path, it will be
searched for in the directories listed in $LOAD_PATH”

But when i output the $LOAD_PATH before the require statement on mri
2.1.1 i got following:

/home/benny/.rubies/mri-2.1.1/lib/ruby/site_ruby/2.1.0
/home/benny/.rubies/mri-2.1.1/lib/ruby/site_ruby/2.1.0/x86_64-linux
/home/benny/.rubies/mri-2.1.1/lib/ruby/site_ruby
/home/benny/.rubies/mri-2.1.1/lib/ruby/vendor_ruby/2.1.0
/home/benny/.rubies/mri-2.1.1/lib/ruby/vendor_ruby/2.1.0/x86_64-linux
/home/benny/.rubies/mri-2.1.1/lib/ruby/vendor_ruby
/home/benny/.rubies/mri-2.1.1/lib/ruby/2.1.0
/home/benny/.rubies/mri-2.1.1/lib/ruby/2.1.0/x86_64-linux

After the require statment for example i wanna use stackprof the
$LOAD_PATH is:

/home/benny/.gem/ruby/2.1.1/extensions/x86_64-linux/2.1.0-static/stackprof-0.2.6
/home/benny/.gem/ruby/2.1.1/gems/stackprof-0.2.6/lib
/home/benny/.rubies/mri-2.1.1/lib/ruby/site_ruby/2.1.0
/home/benny/.rubies/mri-2.1.1/lib/ruby/site_ruby/2.1.0/x86_64-linux
/home/benny/.rubies/mri-2.1.1/lib/ruby/site_ruby
/home/benny/.rubies/mri-2.1.1/lib/ruby/vendor_ruby/2.1.0
/home/benny/.rubies/mri-2.1.1/lib/ruby/vendor_ruby/2.1.0/x86_64-linux
/home/benny/.rubies/mri-2.1.1/lib/ruby/vendor_ruby
/home/benny/.rubies/mri-2.1.1/lib/ruby/2.1.0
/home/benny/.rubies/mri-2.1.1/lib/ruby/2.1.0/x86_64-linux

This is kinda weird for me because in the documentation there is said a
require statement tries to load a library from the $LOAD_PATH when it’s
not a absolute path and doesn’t modify it?

Is there anything else going on?
Maybe rubygems itself just includes gems to the load path if they are
required explicitly?

Adding the lib directory of a required gem to $LOAD_PATH is documented
by rubygems:

=====
Loading code

At its core, RubyGems exists to help you manage Ruby’s $LOAD_PATH, which
is how the require statement picks up new code. There’s several things
you can do to make sure you’re loading code the right way.


Mangling the load path

Gems should not change the $LOAD_PATH variable. RubyGems manages this
for you. Code like this should not be necessary:

lp = File.expand_path(File.dirname(FILE))
unless $LOAD_PATH.include?(lp)
$LOAD_PATH.unshift(lp)
end

Or:

DIR = File.dirname(FILE)

$LOAD_PATH.unshift DIR unless
$LOAD_PATH.include?(DIR) ||
$LOAD_PATH.include?(File.expand_path(DIR))

When RubyGems activates a gem, it adds your package’s lib folder to the
$LOAD_PATH ready to be required normally by another lib or application.
It is safe to assume you can then require any file in your lib folder.

Found the interesting part for me:

Just if anyone needs this too :slight_smile:

okay thx to clear this up :slight_smile:
just wondered how the $LOAD_PATH got modified by requiring a gem

i’ll dig into the rubygems source to make it more clearer to me