How does load differ from require in Ruby?
require
searches for the library in all the defined search paths and also appends
.rb or .so to the file name you enter. It also makes sure that a library is only
included once. So if your application requires library A and B and library B requries library A too A would be loaded only once.
With load
you need to add the full name of the library and it gets loaded every time you
call load
- even if it already is in memory.
What is the difference between require and load?
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.
Understanding the difference between `load`, `require`, and `require_relative`
load
is used when you want to import a file irrespective of whether it has been already imported. require
or require_relative
is used when you want to import a file only if it has not been already.
From this, it follows that the former is used when the imported file is the object of analysis (data file), whereas the latter is used to provide some features to be used in the program (part of the program, library, framework).
While require
can only handle paths relative to $:
, require_relative
is an extension that can handle paths relative to current directory as well. require_relative
is a superset of require
, and require
can be dispensed (although require_relative
is written using require
, so it has to be rewritten if require
is to be dispensed).
What is the difference between include and require in Ruby?
What's the difference between
"include" and "require" in Ruby?Answer:
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. To run another file without
this added functionality, you can use
the load method.The include method takes all the
methods from another module and
includes them into the current module.
This is a language-level thing as
opposed to a file-level thing as with
require. The include method is the
primary way to "extend" classes with
other modules (usually referred to as
mix-ins). For example, if your class
defines the method "each", you can
include the mixin module Enumerable
and it can act as a collection. This
can be confusing as the include verb
is used very differently in other
languages.
Source
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require
.
Oddly enough, Ruby's require
is analogous to C's include
, while Ruby's include
is almost nothing like C's include
.
Difference between require and load wrt to load and execute
The file is always executed.
In Ruby there is no such thing as loading a file without executing it. Everything is a statement in Ruby and has to be executed. Even class
and def
are just statements.
To illustrate this here's a silly example
class Mystery < [Array, Object, String, Fixnum].sample
...
end
This creates a class with a random superclass. Just to illustrate that Ruby has no declarations but executable statements only.
So there is no such thing as not executing a Ruby file. The difference between load
and require
is as you described, the latter keeps track of all loaded files to avoid reloading them.
PS, and another example
ruby --dump insns -e 'def example; end'
== disasm: <RubyVM::InstructionSequence:<main>@-e>======================
0000 trace 1 ( 1)
0002 putspecialobject 1
0004 putspecialobject 2
0006 putobject :example
0008 putiseq example
0010 opt_send_without_block <callinfo!mid:core#define_method, argc:3, ARGS_SIMPLE>
0012 leave
== disasm: <RubyVM::InstructionSequence:example@-e>=====================
0000 trace 8 ( 1)
0002 putnil
0003 trace 16 ( 1)
0005 leave
As you can see def example; end
is a statement and internally calls the define_method
method. So def
is just syntactic sugar for a method call.
When to use `require`, `load` or `autoload` in Ruby?
Generally, you should use require
. load
will re-load the code every time, so if you do it from several modules, you will be doing a lot of extra work. The lazyness of autoload
sounds nice in theory, but many Ruby modules do things like monkey-patching other classes, which means that the behavior of unrelated parts of your program may depend on whether a given class has been used yet or not.
If you want to make your own automatic reloader that loads your code every time it changes or every time someone hits a URL (for development purposes so you don't have to restart your server every time), then using load
for that is reasonable.
When to use load rather than require in Ruby?
If you need to force something to reload (a common example would be a web server or a test server). You should use autoload when there is a reasonable chance some piece of code won't get hit, or you want to address app load time issues. You should use require at all other times.
What exactly Require and Load does in ruby
I simply like to explain you about those two statements , those two are not functions in rails . Rails uses cache to cache the file when its loaded previously . when you get your cache true , then it uses require otherwise it uses load statement to load independent on cache .
I simply like to say that require is used to cache the file thats already loaded and load always hit the server to load files .
Related Topics
How to Use Global Variables or Constant Values in Ruby
How to Write Postgresql Functions on Ruby on Rails
How to Make an Http Get With Modified Headers
Ruby: How to Write Multi-Line String With No Concatenation
Rvm 'Not Found' After Successful Usage and a Few Days Later
How to Set Sslcontext Options in Ruby
Uninstall All Installed Gems, in Osx
Getting Fields_For and Accepts_Nested_Attributes_For to Work With a Belongs_To Relationship
Set Global Default Encoding For Ruby 1.9
What Does Class_Eval ≪≪-"End_Eval", _File_, _Line_ Mean in Ruby
How to Convert Datetime.Now to Utc in Ruby
Matching Balanced Parenthesis in Ruby Using Recursive Regular Expressions Like Perl
Gem Eventmachine Fatal Error: 'Openssl/Ssl.H' File Not Found
How to Install Ruby-Debug When Needing Necessary Libraries And/Or Headers