Require and $LOAD_PATH

Hi there,

I am new to ruby, my understanding is require statement only search the
filename in the $LOAD_PATH, then why after I install a new ruby gem, I
don’t need to add it to the $LOAD_PATH, and I can use it via “require”
directly? It sounds like magic to me.

Here is what I did as a test:

I created a test gem called “hello” and installed it locally

here is my test.rb

puts “before require:”
puts $LOAD_PATH

require ‘hello’
puts “after require:”
puts $LOAD_PATH

And here is the output
before require:
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby/2.1.0
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby/2.1.0/i686-linux
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/vendor_ruby/2.1.0
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/vendor_ruby/2.1.0/i686-linux
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/vendor_ruby
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0/i686-linux
after require:
/usr/local/rvm/gems/ruby-2.1.4/gems/hello-0.0.0/lib
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby/2.1.0
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby/2.1.0/i686-linux
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/site_ruby
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/vendor_ruby/2.1.0
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/vendor_ruby/2.1.0/i686-linux
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/vendor_ruby
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0
/usr/local/rvm/rubies/ruby-2.1.4/lib/ruby/2.1.0/i686-linux

It sounds like after the “require hello”, ruby added the gem path
“/usr/local/rvm/gems/ruby-2.1.4/gems/hello-0.0.0/lib” to $LOAD_PATH.

Is there any document on this behavior?

Thanks,
Stone

Thanks for the help Jesus!

  • Stone

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs