require v load

A

ANDREW BAINE

Why would require work where load does not? See the output below:

irb(main):001:0> filename = 'lib/sudoku/cell'
=> "lib/sudoku/cell"
irb(main):002:0> load filename
LoadError: no such file to load -- lib/sudoku/cell
from (irb):2:in 'load'
from (irb):2
irb(main):003:0> require filename
=> true
irb(main):004:0> c = Sudoku::Cell.new
=> #<Sudoku::Cell:0x2c20258 @number = nil>

Thanks for any help from an eager Ruby convert
 
R

Robert Klemme

ANDREW said:
Why would require work where load does not? See the output below:

irb(main):001:0> filename = 'lib/sudoku/cell'
=> "lib/sudoku/cell"
irb(main):002:0> load filename
LoadError: no such file to load -- lib/sudoku/cell
from (irb):2:in 'load'
from (irb):2
irb(main):003:0> require filename
=> true
irb(main):004:0> c = Sudoku::Cell.new
=> #<Sudoku::Cell:0x2c20258 @number = nil>

Thanks for any help from an eager Ruby convert

These are two completely different mechanisms: require loads a file only
once and it looks in the search path for libs. load only tries to
resolve the given filename (absolute or relative) and will load the file
as many times as it is invoked.

robert
 
A

ANDREW BAINE

Thanks, Robert.

Let me follow up, though. In my example,
load filename failed and then
require filename
succeeded. I infer from your response that this means that filename is
found in the search path (by require) but not as an absolute or relative
path (by load). Does that sound right?

How can I find out what directories are included in the search path?
 
T

ts

A> succeeded. I infer from your response that this means that filename is
A> found in the search path (by require) but not as an absolute or relative
A> path (by load). Does that sound right?

Well not exactly, here an example

moulon% pwd
/tmp
moulon%

moulon% ls net/telnet*
ls: net/telnet*: No such file or directory
moulon%

moulon% ruby -e 'load "net/telnet"'
-e:1:in `load': no such file to load -- net/telnet (LoadError)
from -e:1
moulon%

moulon% ruby -e 'load "net/telnet.rb"'
moulon%

You must give the complete filename (with the extension) with load

With require, you can just write

moulon% ruby -e 'require "net/telnet"'
moulon%

A> How can I find out what directories are included in the search path?

the global variable $LOAD_PATH
 
A

ANDREW BAINE

Case closed: I wasn't adding ".rb" to the end of the filename. Require
could find it but load couldn't. Thanks Guy and Robert.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,244
Latest member
cryptotaxsoftware12

Latest Threads

Top