“Class are itself objects” - this is statement is making me too
confused,when trying to feel the concept at its core.
…
Can anyone give me here some light?
Think of a class as a set of instructions for making something. That
something, is an object of that class. So if you declare class
Widget, and do “w = Widget.new”, w is an object of class Widget, or
for shorthand, w is a Widget.
BUT (the tricky part) a class itself is also something made using a
set of instructions. That set of instructions is the class called
Class. (You can think of that as being a set of instructions for
writing instructions, like a manual on writing manuals.) So a class
is also an object, of class Class.
To top things off, there is also a class called Object, that
everything else inherits from.
(Well, technically not any more. Now there’s BasicObject, which is
even more basic than Object. But that’s another story.)
It becomes a bit clearer when you realize you COULD do “Class.new” and
fill it in with all the various things needed to define a class. So
in that respect, Class is just another class.
I was actually trying to see in how many ways class objects can call
methods?
Class objects do not actually call methods. Class objects are just
instances of the class Class. For example, you can call Class#new on
them,
or #object_id for example.
When the interpreter creates an object it internally associates the
object
with the class it is an instance of. For example, “” is an instance of
String, and String is an instance of Class. In both cases, conceptually
you
have to visualize the instance has an internal slot that points to the
class. When you call self.class you are accessing that slot.
There is a difference, instances of the Class class have an internal
method table associated to them. That table stores the instance method
definitions you define, generally using the def keyword. That is a
builtin
behaviour.
Method calling is done by the interpreter. When you invoke a method the
interpreter checks that slot and looks for the method in the associated
class (and more).
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.