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
?
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 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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With