[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

include vs. extend

Daniel DeLorme

7/11/2006 12:13:00 AM

I was under the impression that include and extend were basically module-level
and object-level versions of the same thing, that including a module at the
class level had the same effect as extending an object. But it seems there is a
big difference:

class Foo
include Enumerable
end
class Bar
def initialize
extend Enumerable
end
end
(class << Foo.new;self;end).ancestors #=> [Foo, Enumerable, Object, Kernel]
(class << Bar.new;self;end).ancestors #=> [Enumerable, Bar, Object, Kernel]

This makes a whole world of difference when you want to wrap certain methods
with additional functionality. In such cases you *have* to use extend (or ugly
techniques like aliasing the old method). Why the difference? In what cases
should I use include and what cases should I use extend?

Daniel

2 Answers

dblack

7/11/2006 12:25:00 AM

0

Kent Sibilev

7/11/2006 12:30:00 AM

0

In the first case, the proxy that refers to the Enumerable module is
inserted between Foo class and Object class. In the second case, an
instance of a Bar class during initialization receives a new class
which is the same proxy object and this proxy's superclass is Bar
class. BTW, check out this book at http://rhg.rub.... It has a
very nice chapter about internal structure of Ruby object model.

Kent.

On 7/10/06, Daniel DeLorme <dan-ml@dan42.com> wrote:
> I was under the impression that include and extend were basically module-level
> and object-level versions of the same thing, that including a module at the
> class level had the same effect as extending an object. But it seems there is a
> big difference:
>
> class Foo
> include Enumerable
> end
> class Bar
> def initialize
> extend Enumerable
> end
> end
> (class << Foo.new;self;end).ancestors #=> [Foo, Enumerable, Object, Kernel]
> (class << Bar.new;self;end).ancestors #=> [Enumerable, Bar, Object, Kernel]
>
> This makes a whole world of difference when you want to wrap certain methods
> with additional functionality. In such cases you *have* to use extend (or ugly
> techniques like aliasing the old method). Why the difference? In what cases
> should I use include and what cases should I use extend?
>
> Daniel
>
>


--
Kent
---
http://www.dat...