Object to which a meta class belongs?

E

Erik Veenstra

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.erikveen.dds.nl/

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

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__

----------------------------------------------------------------
 
S

Sean O'Halpin

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.erikveen.dds.nl/

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

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
 
E

Erik Veenstra

It does work work, but...

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

Thanks.

gegroet,
Erik V. - http://www.erikveen.dds.nl/

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

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

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

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,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top