| Start |
|---|
Inheritance of Singleton Class Subclassing also Subclasses Singleton ClassExtending or Including a Module does not Extend Singleton Class |
| Singleton classes All objects are instances of a class. However, that is not the whole truth. In Ruby, every object also has a somewhat hidden singleton class. This is what allows methods to be defined on individual objects. The singleton class sits between the object itself and its actual class, so all methods defined on it are available for that object, and that object only. The example above could have been written using Which is the same as defining the method on Before the existence of |
| Introduction Ruby has three types of objects:
Each object has a class which contains its methods: Objects themselves can't contain methods, only their class can. But with singleton classes, it is possible to add methods to any object including other singleton classes.
Ruby creates singleton classes on demand. Accessing them or adding methods to them forces Ruby to create them. |
| Accessing Singleton Class There are two ways to get singleton class of an object
|
| Accessing Instance/Class Variables in Singleton Classes Singleton classes share their instance/class variables with their object. Blocks close around their instance/class variables target. Accessing instance or class variables using a block in |
| Message Propagation with Singleton Class Instances never contain a method they only carry data. However we can define a singleton class for any object including an instance of a class. When a message is passed to an object (method is called) Ruby first checks if a singleton class is defined for that object and if it can reply to that message otherwise Ruby checks instance's class' ancestors chain and walks up on that. |
| Reopening (monkey patching) Singleton Classes There are three ways to reopen a Singleton Class
Every object has a singleton class which you can access Syntax
RemarksSingleton classes only have one instance: their corresponding object. This can be verified by querying Ruby's Using References: |
Read Article
https://develop.horje.com/learn/1434/reference