Object to which a meta class belongs?

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

On 7/24/06, Erik V. [email protected] wrote:

     def belongs_to

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

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

On 7/25/06, Erik V. [email protected] wrote:

It does work work, but…

… It’s even slower. Much slower. ;]

Thanks.

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

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

Regards,
Sean

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs