Singleton class access

Adding the following object to an object should allow me to get a singleton class of any object.

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

I had a Powerball class that I created this way

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

He gave me this conclusion

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

So, two instances of the powerball class have unique identifiers, and calling singleton_class directly in the class does not give the identifier of the object.

Questions

  • Are identifiers unique because each instance has a singleton class?

  • I understand that self inside the class simply returns the ie Class: Powerball class, but since the class is an object, should it not have an identifier? Is there any way to access this identifier?

+4
source share
1 answer

You need to understand that the singleton class belongs to the instance. The first two singleton in your code belonged to two different Powerball instances. (Yes, each instance has its own singleton class — it's called singleton because only one instance ever belongs to it.) The third and fourth singleton were the same — the singleton class of the Powerball class itself, which, of course, is the same object in in both cases.

Why don't you try exploring 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.

+2
source

All Articles