My question is similar to "What is the difference between include and extend in Ruby?".
What's the difference between require
and include
in Ruby? If I just want to use the methods from a module in my class, should I require
it or include
it?
Ruby
require
is more like "include" in other languages (such as C). It tells Ruby that you want to bring in the contents of another file. Similar mechanisms in other languages are:using <namespace>
directive in C#.import <package>
in Java.Ruby
include
is an object-oriented inheritance mechanism used for mixins.There is a good explanation here:
Emphasis added.
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'sinclude
, while Ruby'sinclude
is almost nothing like C'sinclude
.'Load'- inserts a file's contents.(Parse file every time the file is being called)
'Require'- inserts a file parsed content.(File parsed once and stored in memory)
'Include'- includes the module into the class and can use methods inside the module as class's instance method
'Extend'- includes the module into the class and can use methods inside the module as class method
Have you ever tried to
require
a module? What were the results? Just try:Modules cannot be required, only included!
Include
Require
So it keeps track of whether that library was already loaded or not. You also don’t need to specify the “.rb” extension of the library file name. Here’s an example of how to use require. Place the require method at the very top of your “.rb” file:
Load
Extend
Include When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module.
Load The load method is almost like the require method except it doesn’t keep track of whether or not that library has been loaded. So it’s possible to load a library multiple times and also when using the load method you must specify the “.rb” extension of the library file name.
Require The require method allows you to load a library and prevents it from being loaded more than once. The require method will return ‘false’ if you try to load the same library after the first time. The require method only needs to be used if library you are loading is defined in a separate file, which is usually the case.
You can prefer this http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/