NOTE:
I’m not a “computer scientist”.
So, I would really appreciate a revision of the text bellow by a “well
grounded rubyist”, a "confident ruby"ist, a "ruby best practice"ing
one or any senior rubyist that loves this language as much as I do.
Any feedback are really welcome!
Hi Arup, (take the text bellow at your own risk )
I would disagree with you
Classes in Ruby are objects also.
Think of them as objects that has special methods (#new, #alocate,
#initialize) and are capable of creating other objects each one of
them being instances of its own metaclass that inherits from this
Class object.
So a Class object is kind of a “formula” to summon objects and their
metaclasses.
class Foo
def hello
puts “Hello from #hello instance method defined on Foo being
called at #{self}”
end
def hi
puts “Hi from #hi instance method defined on Foo being called at
#{self}”
end
end
foo = Foo.new
Sfoo = foo.singleton_class
class Sfoo
def hello
puts “Hello from #hello instance method defined on Sfoo being
called at #{self}”
puts “Calling super…”
super
end
end
foo.hello will call the Sfoo#hello and from them it explicitly call
super that will call a method with the same name on the superclass
foo.hello
But, if foo is an instance of Sfoo and not of Foo, how can I call #hi
on foo?
foo.hi # It works
That’s because there’s no #hi method defined on Sfoo
Sfoo.instance_methods(false) #=> [:hello]
Foo.instance_methods(false) #=> [:hello, :hi]
And Foo is the superclass of Sfoo and “inherits” methods from it.
Sfoo.superclass #=> Foo
So, If I want to know what Class object created a given object I
would call #class on it.
That was the “formula” used to do it, and it’s also the superclass
of its metaclass.
foo.class #=> Foo
If I want to know what (real) class the object is a direct instance
of, I would call #singleton_class on it
This is to what the “klass” pointer is really pointing.
That’s why there’s two methods with the word “class” on the name
foo.singleton_class #=> #<Class:#Foo:0x00000001fb84b0>
There’s a short video here that clarifies it a little bit.
http://drtom.ch/posts/2011/12/11/Rubys_Object_Model_and_Eigenclasses/
And the book “Metaprogramming Ruby: Program Like the Ruby Pros” by
Paolo Perrotta treats this subject pretty deeply.
Now let’s wait for some feedback just to be sure there’s no
misinformation in my post.
Best regards,
Abinoam Jr.