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
-
Are the ids unique because each instance has a singleton class?
-
I understand that
selfwithin 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?
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:
And also, in Ruby 1.9.x, #singleton_class is a built-in method.