[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

New object without initialize() question

Its Me

5/13/2006 2:20:00 PM

Where/how do I define a method to construct a new object without calling
initialize?

e.g. I want

class Foo
def special_init *args
end
end

Foo.construct my_args
# get a new Foo without calling #initialize
# calls special_init instead of #initialize

Thanks!


5 Answers

Tim Hunter

5/13/2006 2:35:00 PM

0

itsme213 wrote:
> Where/how do I define a method to construct a new object without calling
> initialize?
>
> e.g. I want
>
> class Foo
> def special_init *args
> end
> end
>
> Foo.construct my_args
> # get a new Foo without calling #initialize
> # calls special_init instead of #initialize
>
> Thanks!
>
>

ri Class#allocate
--------------------------------------------------------- Class#allocate
class.allocate() => obj
------------------------------------------------------------------------
Allocates space for a new object of class's class. The returned
object must be an instance of class.

Ross Bamford

5/13/2006 2:37:00 PM

0

On Sat, 13 May 2006 15:20:11 +0100, itsme213 <itsme213@hotmail.com> wrote:

> Where/how do I define a method to construct a new object without calling
> initialize?
>
> e.g. I want
>
> class Foo
> def special_init *args
> end
> end
>
> Foo.construct my_args
> # get a new Foo without calling #initialize
> # calls special_init instead of #initialize
>

This may or may not be a good idea (I'll stay on the fence :)) but here's
a way to do it:

class Foo
class << self
def construct(*args, &blk)
o = allocate
o.special_init(*args,&blk)
o
end
end

def special_init(*args)
@test = args
end
end

p Foo.construct([1,2,3])
# => #<Foo:0xb7f859f8 @test=[[1, 2, 3]]>

--
Ross Bamford - rosco@roscopeco.remove.co.uk

ts

5/13/2006 2:38:00 PM

0

>>>>> "i" == itsme213 <itsme213@hotmail.com> writes:

i> e.g. I want

Well, you can try

i> class Foo
i> def special_init *args
i> end

def self.construct(*args)
allocate.special_init(*args)
end

i> end


--

Guy Decoux

Its Me

5/13/2006 4:35:00 PM

0

Ah, #allocate is just the ticket.

Thanks!

"ts" <decoux@moulon.inra.fr> wrote in message
news:rfciroaourb.fsf@moulon.inra.fr...
>>>>>> "i" == itsme213 <itsme213@hotmail.com> writes:
>
> i> e.g. I want
>
> Well, you can try
>
> i> class Foo
> i> def special_init *args
> i> end
>
> def self.construct(*args)
> allocate.special_init(*args)
> end
>
> i> end
>
>
> --
>
> Guy Decoux


Gene Tani

5/14/2006 5:47:00 PM

0


Ross Bamford wrote:
> On Sat, 13 May 2006 15:20:11 +0100, itsme213 <itsme213@hotmail.com> wrote:
>
> This may or may not be a good idea (I'll stay on the fence :)) but here's
> a way to do it:
>

some pointers to production code in the "allocate" discussion (and what
they had to do before allocate
http://whytheluckystiff.net/articles/rubyOneEi...