Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between require and load?

What is the difference between using:

require 'digest'

and

load 'digest'
like image 372
Leonardo Wolter Avatar asked Feb 01 '13 13:02

Leonardo Wolter


People also ask

What is difference between require and include in Ruby?

What's the difference between "include" and "require" in Ruby? The include and require methods do very different things. The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice.

What is the use of require in Ruby?

In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.

What is the difference between extend and include in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

What is the purpose of load Auto_load and Require_relative in Ruby?

It performs the inclusion operation and reprocesses the whole code every time the load is being called. -Auto_load: this initiates the method that is in hat file and allows the interpreter to call the method. -require_relative: allows the loading to take place of the local folders and files.


1 Answers

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.

like image 185
Sergio Tulentsev Avatar answered Nov 15 '22 17:11

Sergio Tulentsev