I'm a C++ programmer learning Ruby. In a beginner book I read:
"A class is itself an object, even if you don’t directly instantiate it."
I don't know how to interpret that.
In C++, with the exception of typeid
et al, there's no language-visible runtime representation of a class. You can say class Foo {};
, but then you can't say &Foo
. (You can get the typeid
/ address of the typeinfo
object, which is a bastardized version of a class object).
In Ruby, classes are objects. Anything you can do with an object, you can do with a class since it is an object. For example, in Ruby you can foo.send(...)
to any object foo
. Since a class is an object, you can just as well as Foo.send(...)
.
The part about "you didn't instanciate it" refers to the fact that usually you say foo = Foo.new
in Ruby but you don't need to say that for classes. The class object is created by the runtime. (In fact, class Foo; end
in Ruby is pretty similar to Foo = Class.new
.)
In Ruby, everything is an object. That includes classes. So when you declare
class Thing
end
You've made an instance of the Class
class called Thing
. It's identical to
Thing = Class.new
which would be "directly instantiating" the instance of Class
.
Everything in Ruby is an object, even the classes themselves.
class Test
def self.foo
"bar"
end
def yin
"yang"
end
end
# This creates a new instance and calls #yin
Test.new.yin # => "yang"
# This calls the #foo method on the Test class object.
Test.foo # => "bar"
In some other languages, you have something called 'abstract classes'. These things are not objects themselves and can't really do anything. They're really more like a template for creating an actual object. An actual object can do things like run methods, accept arguments, etc. An abstract class can't do any of that and exists mainly to create a real object. When an object is created from them, it's called 'instantiating' an object.
Now in ruby, you don't have abstract classes. The class you use to derive objects from (instantiate) is sort of like an abstract class in some ways. But unlike abstract classes, this class in ruby can already do things itself.
This is what the statement you quoted "A class is itself an object, even if you don’t directly instantiate it" is trying to make clear. It isn't virtual in the sense of an abstract class. Rather it's already a full fledged object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With