Mental Model of Ruby Classes
Fri Oct 28 2022
About:
If you have started learning ruby recently, you might have got baffled by the facts that,
Class
is a child of the class Module
Module
is of type Class
.And, if you don’t know how to wrap your head around this paradox, you’re not alone. At our TechConative Study Group, we spent some time as well, and we arrived at a reasonable Mental Model on how this could be possible.
The below understanding would set the perspective and get a Mental Model of it.
Note: The keywords in
code block
represents ruby code. Hence, if you seeClass
that represents the actual Class in ruby. Whereas class means any class.
Classes are Object:
Contrary to the intuitive thought (for folks from Java, C#, etc.) to think Classes as fixed blue-prints, Classes in Ruby
are actually objects of the class Class
.
Still, How come Class.class
is Class
. How can a class be created from itself?
How can we have something which is created with a blueprint of its own definition?
How come Module.class
is Class
when Class.superclass
is Module
? How can we have something be created with a
blueprint of something that is yet to be created extending it?
All Objects(hence classes) as Map(/Dict/Hash):
The problem is, if we think classes and objects in the below sequence, Define a blueprint(representing the attributes, methods and superclass) . Define entities(object) following the blueprint.
Instead, what if we have a Class as Maps(/Dict/Hash) and the blueprints (representing the attributes, methods and superclass) are actually set after the creation? i.e.,
With this model, you don’t have to have the “blueprint” first to create an object. You can create the object first and
define the type later. I.e., Create an object for class Class
and then set the type as Class
.
From the ruby source:
On doing a quick check to validate the theory, had a look into the ruby source, which I assume is actually where the basic classes are defined.
Seems like,
Though we haven't got too much into the implementation, this mental model solves the paradox!
We would love to hear from you! Reach us @
info@techconative.com