CodeProject · Ruby

Crazy Ctor Concept in Ruby Part 2

Dear Reader,

This is an extension to my old post about ctor concept in Ruby where in i talked about how Ctor concept has been implemented in Ruby and it’s quite different from other languages at least in 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 2 different stages.
At first i was confused on this statement, where in it said Initialize is the first method called when you try to create a new object. So later findings of mine revealed that, creation happens by calling Class.new method and initialization happens by calling Initialize method.

In ruby, every time you create new on a class then ruby creates object of type Class by calling Class.new method. This new method further calls allocate method to create a new object. So this step is actually called Construction, hence its quite different. This operation happens behind the scenes, hence from the developer perspective there is no constructor in ruby to explicitly represent as such.

But the advantage here is that you can override Class.new method in your type. By doing so, you get an advantage of making your type as 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 2 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 did not use it, then new() will just be an instance method like other methods in your class that means it will not override Class.new() method, 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 had to provide a method (perhaps class method) which would do the same, but this interface looks nice and Class.new is used by default every where to create objects of a type and its less confusing as well 🙂

Happy coding 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s