views:

3980

answers:

3

My question is similar to this one over here about include and extend.

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?

+16  A: 

From here:

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.

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".

HanClinto
+6  A: 

Ruby require is more like "include" in other languages (such as C). This tells Ruby that you want to bring in the contents of another file.

Ruby include is an OO inheritance mechanism used for mixins.

There is a good explanation here.

bradheintz
A: 

Ruby include is like Java implements keyword, but not the same. remember in Java implements is like a contract.

Carlos