Reputation: 5616
I would like to know is there any ways to check is singleton class of an object already created?
ex: obj.singleton_class_defined?
Upvotes: 0
Views: 185
Reputation: 66837
The singleton class of an object is always defined. In 1.8.7 you can use singleton_methods
to see if an object already has associated singleton methods:
>> foo = ''
=> ""
>> foo.singleton_methods
=> []
1.9.2 (possibly also earlier 1.9s, I can't remember) also has a method called singleton_class
, which saves you from doing the class << self; self ; end
thing we all got used to:
>> foo.singleton_class #=> #<Class:#<String:0x00000100ba5648>>
Edit:
Since you tagged this with "object-model", I also wanted to recommend the following link:
http://www.hokstad.com/ruby-object-model.html
To quote from there:
A meta-class is for all practical purposes an actual class. It is an object of type Class. The only thing "special" about a meta-class is that it is created as needed and inserted in the inheritance chain before the objects "real" class. So inside the MRI interpreter object->klass can refer to a meta-class, that has a pointer named "super" that refers to the next class in the chain. When you call object.class in MRI, the interpreter actually "skips" over the meta-class (and modules) if it's there.
Upvotes: 3