Ruby Require versus load difference

Source: Internet
Author: User

What's the difference between "require" in Ruby, "load" and "include"? Require "and" load "purposes are consistent, used to load the new library," include "is used to mix-in module

"require" can load a a.rb file, and it can omit ". RB", and it will only load at the first time, if again "require" will be ignored
Java code require ' a ' a = A.new
Require ' a '
a = a.new


"Load" and "require", but to use the A.RB full name, and must reload each time
Java code load ' a.rb ' a = a.new
Load ' a.rb '
a = a.new


the order in which the library is loaded. Java-like class Path,ruby this information on the "$:" System global variable, you can use Rubylib or ruby-i to add a new loading directory
Java code puts $:
Puts $:


"include" is used to mix-in a module to reduce the length of writing
Java code require ' Webrick ' include Webrick # can be used without server = Webrick::httpserver.new (...) server = Httpserver.new (...)
Require ' Webrick '
include Webrick

# can be used without server = Webrick::httpserver.new (...)
Server = Httpserver.new (...)


So what's the use of load?
Rails programs use load rather than require to load libraries
In development mode, when you modify a piece of code, you do not need to restart the server, your code changes will be automatically reload, which is the role of load
And if you use require, multiple require won't work.
For large ruby programs like rails, using multiple files and Require/load/include makes your program very easy to organize and partition modules
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: