Main Content

Load path, load and require in Ruby, and a change from 1.8 to 1.9

Archive - Originally posted on "The Horse's Mouth" - 2012-06-24 08:59:40 - Graham Ellis

Ruby loads files through the require command from a list of directories held in the $: special variable, also known as $LOAD_PATH.

Up to and including Ruby 1.8, this path list included . (the current directory) but from Ruby 1.9 it does not.

Here's a sample program:
  require "direct"
  p Train.new "18:55",96,345


which runs correctly at 1.8.7

  munchkin:rpj12 grahamellis$ /usr/bin/ruby tlo
  ./direct.rb loaded and initialised
  #<Train:0x102c3a840 @seats=345, @length=96, @mycount=1, @time="18:55">


  munchkin:rpj12 grahamellis$ /usr/bin/ruby -v
  ruby 1.8.7 (2010-01-10 patchlevel 249) [universal-darwin11.0]


However, I get an error at 1.9.3

  munchkin:rpj12 grahamellis$ ruby tlo
  /Users/grahamellis/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- direct (LoadError)
    from /Users/grahamellis/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from tlo:8:in `<main>'


As a quick (and very dirty) fix, you can add . to the path:
  $:.push(".")
  require "direct"
  p Train.new "18:55",96,345


And the program will work at 1.8 and 1.9, even with the required file in the current running directory.

As an alternative, the require can be modified:
  require "#{File.dirname(__FILE__)}/direct"
  p Train.new "18:55",96,345


There is also a load command in Ruby.. Differences:
require will only bring in a file once, load will bring it in multiple times
require will automatically add extensions .rb, .so, .o and .dll; with load you must be specific
require uses the $: / $LOAD_PATH, but load does not.

And so
  load "direct.rb"
  p Train.new "18:55",96,345

works in both 1.8.7 and 1.9.3. But having said that, require is recommended in most circumstances.