Reputation: 21
I am new to ruby. I have understood the singleton class concept of ruby but I have one question that at what point ruby creates a singleton class for objects. I mean when objects define their own method(which is not in its ancestor class or super class) or when the object is created at runtime. I am clear with the concept that when a Class or object define methods as their own methods an anonymous class inserted between the object and its class which is know as 'Singleton Class'. But looking at this thread Difference between class variables and class instance variables? in banister answer he has used something like
hello.singleton_class.class_variable_get(:@@class_var)
where hello is an object of a class Hello
which has class variable @@class_var
.
Why do we have to use 'singleton_class' in
hello.singleton_class.class_variable_get(:@@class_var)
Does the singleton class also get inserted when you define class variables in a class?
Upvotes: 2
Views: 110
Reputation: 4551
If you look at the source code of singleton_class
you will find that it just forwards to the C-function rb_singleton_class
(at least it does for MRI). If you dive further into that you will find some C-code that basically boils down to an elaborate set of tests for exceptional cases and then the singleton class is created if all goes well.
Conceptionally the singleton_class
is just what its name suggests, a singleton Class
object. As every well behaved singleton should it will be created when it is first accessed. Wether this happens because you define a singleton method or because you access singleton_class
explicitly is entirely up to your program. For most objects there will never be a call to singleton_class
and therefore the Class
object will not be created at all. If that would not be the case it would hardly merit the overhead induced by the singleton
mechanics.
I think the author of the answer you cite just wants to illustrate different possibilities of accessing the @@class_var
class variable. Since class_variable_get
is a method of class Class
he will need an instance of that class and since the singleton class is implicitly derived from the regular parent class he can use it to. In the example he might also use
hello.class.class_variable_get(:@@class_var)
to the same effect.
Upvotes: 1