4

Adding the following code to an object is supposed to allow me to retrieve the singleton class of any object.

class Object
    def singleton_class
        class << self; self; end
    end
end

I had a Powerball class, which I instantiated this way

puts Powerball.new.singleton_class
puts Powerball.new.singleton_class
puts Powerball.singleton_class
puts Powerball.singleton_class

It gave me this output

#<Class:#<Powerball:0x007fd333040548>>
#<Class:#<Powerball:0x007fd333040408>>
#<Class:Powerball>
#<Class:Powerball>

So, the two instances of the powerball class have unique ids, while calling singleton_class directly on the class doesn't yield an object id.

Questions

  1. Are the ids unique because each instance has a singleton class?

  2. I understand that self within a class just returns the Class i.e. Class:Powerball, but since a class is an object, shouldn't it also have an id? Is there a way to access that id?

Mischa
  • 42,876
  • 8
  • 99
  • 111
BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134
  • An interesting article on singleton class can be found on a Devalot blog from the comment to this answer http://stackoverflow.com/questions/13850971/why-are-symbols-in-ruby-not-thought-of-as-a-type-of-variable/13871724#13871724 – BernardK Jan 03 '13 at 08:59

1 Answers1

2

You'll have to understand that singleton class belongs to an instance. First two singletons in your code belonged to two different Powerball instances. (Yes, each instance has its very own singleton class – it's called singleton because only that one instance ever belongs to it.) The 3rd and 4th singleton was the same - singleton class of the Powerball class itself, which, of course, is the same object in both cases.

Why don't you try investigating by yourself:

class Kokot; end
puts Kokot.object_id
puts Kokot.singleton_class.object_id

And also, in Ruby 1.9.x, #singleton_class is a built-in method.

Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74