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__

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

How about this?

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

Regards,
Sean

···

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.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__

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

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

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

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

Regards,
Sean

···

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