Leonardo Wolter
Leonardo Wolter

Reputation: 108

What is the difference between require and load?

What is the difference between using:

require 'digest'

and

load 'digest'

Upvotes: 8

Views: 2345

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

If you require the same file twice, it will be loaded and evaluated only once. load, on the other hand, loads and evaluates the file every time. There are also differences in how actual filename is resolved (thanks, Saurabh).

What does this mean practically?

Let's say we have a library foo

# foo.rb

class Foo
  def bar
    puts 'bar'
  end
  
  def quux
    puts 'quux'
  end
end

Then we have a file which makes some non-idempotent operations. Say, undefines a method

# mod.rb
class Foo
  undef :bar
end

Then, if we require mod.rb twice, nothing bad happens. bar gets successfully undefined.

# main.rb
require './foo'

Foo.instance_methods(false) # => [:bar, :quux]

require './mod'
require './mod'

Foo.instance_methods(false) # => [:quux]
            
            

But if we load mod.rb twice, then second undef operation will fail, because method is already gone:

# main.rb
require './foo'

Foo.instance_methods(false) # => [:bar, :quux]

load 'mod.rb'
load 'mod.rb'

Foo.instance_methods(false) # => 
# ~> mod.rb:2:in `<class:Foo>': undefined method `bar' for class `Foo' (NameError)
# ~>    from mod.rb:1:in `<top (required)>'
# ~>    from -:6:in `load'
# ~>    from -:6:in `<main>'

There's no error with require because in that case undef happens only once. Granted, this example is quite contrived, but I hope it illustrates the point.

Upvotes: 12

Related Questions