23

loadee.rb

puts '> This is the second file.'

loaddemo.rb

puts 'This is the first (master) program file.'
load 'loadee.rb'
puts 'And back again to the first file.'

When I run "ruby loaddemo.rb", This works fine. Both files are in the same directory, and that's the directory I run from.

But if I change the load to a require, and with or without the extension I get:

<internal:lib/rubygems/custom_require>:29:in `require': no such file to load
 -- loadee.rb (LoadError)
        from <internal:lib/rubygems/custom_require>:29:in `require'
        from loaddemo.rb:2:in `<main>'

My question is of course, why isn't require working in this case? It should, right? Do load and require use different paths?

Ruby version 1.9.2

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274

2 Answers2

43

If you provide just a filename to require, it will only look in the predefined $LOAD_PATH directories. However, if you provide a path with your filename, it should work:

puts 'This is the first (master) program file.'
require './loadee.rb'
puts 'And back again to the first file.'

You could also add your project's folder to the load path instead:

$LOAD_PATH.unshift File.dirname(__FILE__)
puts 'This is the first (master) program file.'
require 'loadee.rb'
puts 'And back again to the first file.'

And last, you could just use require_relative instead:

puts 'This is the first (master) program file.'
require_relative 'loadee.rb'
puts 'And back again to the first file.'
7stud
  • 46,922
  • 14
  • 101
  • 127
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • 2
    So why does load work without the path? Does it use a different path variable? – Benjamin Lindley May 14 '11 at 00:12
  • 1
    This is actually listed as a bug for ruby right now. 1.9 removed the "current directory" from the load path when using `require`, but not for `load`. http://redmine.ruby-lang.org/issues/2710 – Dylan Markow May 14 '11 at 00:15
  • 2
    Also, keep in mind that every time you use `load`, it evaluates the entire file, whereas using `require` only evaluates the file the first time you require it. – Dylan Markow May 14 '11 at 00:16
7

Providing a path with the filename seemed not to work for me, and I didn't want to cram a bunch of paths into my $LOAD_PATH.

Checking out the documentation, I found require_relative.

require_relative 'loadee'

Works in both 1.9.2 and 2.1.2.

The documentation indicates that require is not intended to search relative paths at all, and neither is load.

Keen
  • 954
  • 12
  • 19