What is the difference between using:
require 'digest'
and
load 'digest'
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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With