open classes, constructors and blocks

A

Andrea Fazzi

Hi all,

I'd like to re-open a class and to re-initialize its original constructor:

class Foo
def initialize
yield self if block_given?
end
end

class Foo
attr_reader :var
alias foo_initialize initialize
def initialize
foo_initialize
@var = "Foo's instance var"
end
end

Foo.new { |foo| puts foo.var }

The problem is that the block passed to the new constructor is never
called! Why?
Which is the best way to redefine a constructor when a class is re-opened?

Thanks!
Andrea
 
S

Stefano Crocco

Alle 09:49, mercoled=EC 29 novembre 2006, Andrea Fazzi ha scritto:
=A0alias foo_initialize initialize
=A0def initialize
=A0 =A0foo_initialize
=A0 =A0@var =3D "Foo's instance var"
=A0end
end
=20
Foo.new { |foo| puts foo.var }
=20
The problem is that the block passed to the new constructor is never=20
called! Why?

When you call foo_initialize from initialize, you're calling a completely=20
unrelated method, so the block won't be automatically passed to it (this is=
=20
different from when you use super; in that class the block is passed=20
automatically). In your case, you must pass the block in two ways: the firs=
t=20
is to create a new block which simply calls yield:

def initialize
@var=3D"Foo's instance var"
foo_initialize{yield self}
end

(by the way, you need to assign @var before calling foo_initialize if you w=
ant=20
its value to be displayed, otherwise you'll get nil).
The other way is to pass the block as a variable to initialize, using the &=
=20
syntax:

def initialize &block
@var=3D"Foo's instance var"
foo_initialize &block
end

I hope this helps

Stefano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,285
Latest member
CryptoTaxxSoftware

Latest Threads

Top