# Open classes, constructors and blocks

**URL:** <https://www.ruby-forum.com/t/open-classes-constructors-and-blocks/77632>\
**Category:** Ruby\
**Created:** [November 29, 2006, 9:50am UTC](https://www.ruby-forum.com/t/open-classes-constructors-and-blocks/77632 "2006-11-29T09:50:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gendag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f04885/32.png) [@gendag](https://www.ruby-forum.com/u/gendag)\
**Post date:** [November 29, 2006, 9:50am UTC](https://www.ruby-forum.com/t/open-classes-constructors-and-blocks/77632/1 "2006-11-29T09:50:30Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![gendag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f04885/32.png) [@gendag](https://www.ruby-forum.com/u/gendag)\
**Post date:** [November 29, 2006, 10:08am UTC](https://www.ruby-forum.com/t/open-classes-constructors-and-blocks/77632/2 "2006-11-29T10:08:31Z")

</div>

Alle 09:49, mercoledì 29 novembre 2006, Andrea F. ha scritto:

> called! Why?  
> When you call foo\_initialize from initialize, you’re calling a  
> completely  
> unrelated method, so the block won’t be automatically passed to it (this  
> is  
> different from when you use super; in that class the block is passed  
> automatically). In your case, you must pass the block in two ways: the  
> first  
> is to create a new block which simply calls yield:

def initialize  
@var=“Foo’s instance var”  
foo\_initialize{yield self}  
end

(by the way, you need to assign @var before calling foo\_initialize if  
you want  
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 &  
syntax:

def initialize &block  
@var=“Foo’s instance var”  
foo\_initialize &block  
end

I hope this helps

Stefano
