Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "include module" and "extend module" in Ruby? [duplicate]

Tags:

Possible Duplicate:
What is the difference between include and extend in Ruby?

Given:

module my_module   def foo     ...   end end 

Question 1

What is the difference between:

class A   include my_module end 

and

class A   extend my_module end 

Question 2

Will foo be considered an instance method or a class method ? In other words, is this equivalent to:

class A   def foo     ...   end end 

or to:

class A   def self.foo     ...   end end 

?

like image 452
Misha Moroshko Avatar asked Jan 17 '11 02:01

Misha Moroshko


People also ask

What is the difference between include and extend in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

What is the difference between modules and classes in Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

Can a module include another module Ruby?

Actually, Ruby facilitates the use of composition by using the mixin facility. Indeed, a module can be included in another module or class by using the include , prepend and extend keywords.


1 Answers

I wrote a blog posting about this a long time ago here.

When you're "including" a module, the module is included as if the methods were defined at the class that's including them, you could say that it's copying the methods to the including class.

When you're "extending" a module, you're saying "add the methods of this module to this specific instance". When you're inside a class definition and say "extend" the "instance" is the class object itself, but you could also do something like this (as in my blog post above):

module MyModule   def foo     puts "foo called"   end end  class A end  object = A.new object.extend MyModule  object.foo #prints "foo called"     

So, it's not exactly a class method, but a method to the "instance" which you called "extend". As you're doing it inside a class definition and the instance in there is the class itself, it "looks like" a class method.

like image 185
Maurício Linhares Avatar answered Oct 12 '22 23:10

Maurício Linhares