[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Object to which a meta class belongs?

Erik Veenstra

7/24/2006 9:04:00 PM

If a singleton class belongs to an object, it should be
possible to determine to which object it belongs. Is that
possible?

I came up with the code below, but it might not be very fast.

Thanks.

gegroet,
Erik V. - http://www.erikve...

----------------------------------------------------------------

class Object
def metaclass
obj = self

class << self
self
end.instance_eval do
instance_eval <<-END
def belongs_to
ObjectSpace._id2ref(#{obj.__id__})
end
END

self
end
end
end

a = "TEST"

p a.__id__
p a.metaclass.belongs_to.__id__

----------------------------------------------------------------


3 Answers

Sean O'Halpin

7/24/2006 11:20:00 PM

0

On 7/24/06, Erik Veenstra <erikveen@gmail.com> wrote:
> If a singleton class belongs to an object, it should be
> possible to determine to which object it belongs. Is that
> possible?
>
> I came up with the code below, but it might not be very fast.
>
> Thanks.
>
> gegroet,
> Erik V. - http://www.erikve...
>
> ----------------------------------------------------------------
>
> class Object
> def metaclass
> obj = self
>
> class << self
> self
> end.instance_eval do
> instance_eval <<-END
> def belongs_to
> ObjectSpace._id2ref(#{obj.__id__})
> end
> END
>
> self
> end
> end
> end
>
> a = "TEST"
>
> p a.__id__
> p a.metaclass.belongs_to.__id__
>
> ----------------------------------------------------------------
>
>
>

How about this?

class Object
def singleton_of
ObjectSpace.each_object(self) do |obj|
return obj
end
end
end

Regards,
Sean

Erik Veenstra

7/25/2006 6:18:00 AM

0

It does work work, but...

... It's even slower. Much slower. ;]

Thanks.

gegroet,
Erik V. - http://www.erikve...

----------------------------------------------------------------

CPU ELAPSED COUNT CPU/COUNT LABEL
5.850000 6.708499 1 5.850000 :singleton_of
0.560000 1.097820 1 0.560000 :belongs_to

----------------------------------------------------------------

class Module
def singleton_of
res = nil
ObjectSpace.each_object(self) do |obj|
res = obj
end
res
end
end

----------------------------------------------------------------


Sean O'Halpin

7/25/2006 12:31:00 PM

0

On 7/25/06, Erik Veenstra <erikveen@gmail.com> wrote:
> It does work work, but...
>
> ... It's even slower. Much slower. ;]
>
> Thanks.
>
> gegroet,
> Erik V. - http://www.erikve...

Whoops! Knew I should have benchmarked it. :)
ObjectSpace.each_object really is a sledgehammer...

Regards,
Sean