[ruby] What is the difference between include and require in Ruby?

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?

This question is related to ruby include require

The answer is


Below are few basic differences between require and include:

Require:

  1. Require reads the file from the file system, parses it, saves to the memory and runs it in a given place which means if you will even change anything while the script is running than that change will not reflect.
  2. We require file by name, not by module name.
  3. It is typically used for libraries and extensions.

Include:

  1. When you include a module into your class it behaves as if you took the code defined in your module and inserted it in your class.
  2. We include module name, not the file name.
  3. It is typically used to dry up the code and to remove duplication in the code.

From Programming Ruby 1.9

We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.


require(name)

It will return bolean true/false

The name which is passed as parameter to the require, ruby will try to find the source file with that name in your load path. 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. So it keeps track of whether that library was already loaded or not.

include module_name

Suppose if you have some methods that you need to have in two different classes. Then you don't have to write them in both the classes. Instead what you can do is, define it in module. And then include this module in other classes. It is provided by Ruby just to ensure DRY principle. It’s used to DRY up your code to avoid duplication


'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


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/


From Programming Ruby 1.9

We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.


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/


Below are few basic differences between require and include:

Require:

  1. Require reads the file from the file system, parses it, saves to the memory and runs it in a given place which means if you will even change anything while the script is running than that change will not reflect.
  2. We require file by name, not by module name.
  3. It is typically used for libraries and extensions.

Include:

  1. When you include a module into your class it behaves as if you took the code defined in your module and inserted it in your class.
  2. We include module name, not the file name.
  3. It is typically used to dry up the code and to remove duplication in the code.

If you're using a module, that means you're bringing all the methods into your class. If you extend a class with a module, that means you're "bringing in" the module's methods as class methods. If you include a class with a module, that means you're "bringing in" the module's methods as instance methods.

EX:

 module A
   def say
     puts "this is module A"
   end
 end

 class B
   include A
 end

 class C
   extend A
 end

B.say => undefined method 'say' for B:Class

B.new.say => this is module A

C.say => this is module A

C.new.say => undefined method 'say' for C:Class


Have you ever tried to require a module? What were the results? Just try:

MyModule = Module.new
require MyModule # see what happens

Modules cannot be required, only included!


From the Metaprogramming Ruby book,

The require() method is quite similar to load(), but it’s meant for a different purpose. You use load() to execute code, and you use require() to import libraries.


Have you ever tried to require a module? What were the results? Just try:

MyModule = Module.new
require MyModule # see what happens

Modules cannot be required, only included!


If you're using a module, that means you're bringing all the methods into your class. If you extend a class with a module, that means you're "bringing in" the module's methods as class methods. If you include a class with a module, that means you're "bringing in" the module's methods as instance methods.

EX:

 module A
   def say
     puts "this is module A"
   end
 end

 class B
   include A
 end

 class C
   extend A
 end

B.say => undefined method 'say' for B:Class

B.new.say => this is module A

C.say => this is module A

C.new.say => undefined method 'say' for C:Class


From the Metaprogramming Ruby book,

The require() method is quite similar to load(), but it’s meant for a different purpose. You use load() to execute code, and you use require() to import libraries.


require(name)

It will return bolean true/false

The name which is passed as parameter to the require, ruby will try to find the source file with that name in your load path. 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. So it keeps track of whether that library was already loaded or not.

include module_name

Suppose if you have some methods that you need to have in two different classes. Then you don't have to write them in both the classes. Instead what you can do is, define it in module. And then include this module in other classes. It is provided by Ruby just to ensure DRY principle. It’s used to DRY up your code to avoid duplication


'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


  • 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:

  • Ruby include is an object-oriented inheritance mechanism used for mixins.

There is a good explanation here:

[The] simple answer is that require and include are essentially unrelated.

"require" is similar to the C include, which may cause newbie confusion. (One notable difference is that locals inside the required file "evaporate" when the require is done.)

The Ruby include is nothing like the C include. The include statement "mixes in" a module into a class. It's a limited form of multiple inheritance. An included module literally bestows an "is-a" relationship on the thing including it.

Emphasis added.


Include

When you include a module into your class, 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.

module Log 
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass 
  include Log 
  # ... 
end

tc = TestClass.new.class_type # -> success
tc = TestClass.class_type # -> error

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.

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

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.

Extend

When using the extend method instead of include, you are adding the module’s methods as class methods instead of as instance methods.

module Log 
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass 
  extend Log 
  # ... 
end

tc = TestClass.class_type

  • 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:

  • Ruby include is an object-oriented inheritance mechanism used for mixins.

There is a good explanation here:

[The] simple answer is that require and include are essentially unrelated.

"require" is similar to the C include, which may cause newbie confusion. (One notable difference is that locals inside the required file "evaporate" when the require is done.)

The Ruby include is nothing like the C include. The include statement "mixes in" a module into a class. It's a limited form of multiple inheritance. An included module literally bestows an "is-a" relationship on the thing including it.

Emphasis added.


Include

When you include a module into your class, 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.

module Log 
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass 
  include Log 
  # ... 
end

tc = TestClass.new.class_type # -> success
tc = TestClass.class_type # -> error

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.

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

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.

Extend

When using the extend method instead of include, you are adding the module’s methods as class methods instead of as instance methods.

module Log 
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass 
  extend Log 
  # ... 
end

tc = TestClass.class_type

Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to include

"Multiple definition", "first defined here" errors Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 Include PHP file into HTML file Cannot open include file with Visual Studio How to make Apache serve index.php instead of index.html? Include php files when they are in different folders Already defined in .obj - no double inclusions What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files? What is the correct syntax of ng-include? Visual Studio can't 'see' my included header files

Examples related to require

The difference between "require(x)" and "import x" PHP - Failed to open stream : No such file or directory cannot redeclare block scoped variable (typescript) NodeJs : TypeError: require(...) is not a function Include PHP file into HTML file How to make node.js require absolute? (instead of relative) Ruby 'require' error: cannot load such file Nodejs cannot find installed module on Windows is there a require for json in node.js node.js require all files in a folder?