Thursday, November 1, 2012
Ruby Singleton Classes and Relation to Objects and Classes
The methods in the far left column are invoked on the objects defined in the code row. For example, in event sequence 1, the methods are invoked on the module A; event sequence 2, the methods are invoked on class A, and so forth. This shows where Ruby places the method a for each different case of object in the code row. The code in column 8 is a way of putting the singleton class of object o into variable p. Column 9 shows that the o.singleton_class method returns an object equal to the singleton class of object o.
In Ruby, methods, for the purposes of storage, are classified as either singleton or instance methods. Two methods defined on every class will tell you what methods of that class are singleton or instance; namely singleton_methods(false) and instance_methods(false); the false parameter is so that the method only looks one level deep in the class hierarchy, if it's not passed then methods from super classes are also returned. Objects - not classes - only have the singleton_methods method because objects cannot have instance methods; remember objects do not store methods only classes store methods. Class instance methods are are kept in the class that defines them, class singleton methods which are also called class methods - or static methods in java - are kept in the singleton class of the class. Where as, singleton methods defined on an object are kept in the singleton class of the object.
On the other hand, methods are also classified by protection level as either public, private or protected. Each case will have differing visibility effects on the method and will show in the return values of methods, private_methods, public_methods and protected_methods.
ruby, singleton_class, singleton classes, singleton methods, instance methods