This is an extension to my old post about ctor concept in Ruby
where I talked about how the Ctor concept has been implemented in Ruby and it’s quite different from other languages, at least
from C#, because I know that language well.
Further to my findings on this, by reading other books and googling, I found out that actually Creation and Initialization happens at
two different stages.
At first I was confused about this, where it said
Initialize is the first method called when you try to create a new object.
Later findings of mine
revealed that creation happens by calling the
Class.new method and initialization happens by calling
In Ruby, every time you create a new class, Ruby creates an object of type
Class by calling the
Class.new method. This
new method further calls
allocate method to create a new object. This step is actually called Construction,
and it is quite different. This operation happens behind the
scenes, so from the developer perspective, there is no constructor in Ruby.
But the advantage here is that you can override the
Class.new method in your type. By doing so, you get
the advantage of making your type a wrapper class for some other type.
Let me show you a sample code:
As you can see from the above code, I have defined two classes and a
Wrapper class which wraps the creation of my other classes. Now based on some conditions in this wrapper
class, it creates and returns my other types.
One important thing to note in the above code is that I have used
self.new() in the wrapper class. The
new() method should be a class method, hence
new is prefixed with
self keyword. If you do not use it, then
new() will just be an instance method like other methods in your class, that means it will not override
in other words, when you create
Wrapper.new in your usage code, this instance
new method will not be called at all.
If this had not been provided in Ruby, then I would have had to provide a method (perhaps class method) which would do the same, but this interface looks nice and
is used by default every where to create objects of a type, and it is less confusing as well