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?


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 .


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.


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

链接地址: http://www.djcxy.com/p/58024.html

上一篇: 包括,要求和要求

下一篇: include和require在Ruby中有什么区别?