THE BOOK OF RUBY
When a class contains a method named initialize this will be automatically called when an object is created using the new method. It is a good idea to use an initialize method to set the values of an object’s instance variables.
This has two clear benefits over setting each instance variable using methods such set_name. First of all, a complex class may contain numerous instance variables and you can set the values of all of them with the single initialize method rather than with many separate ‘set’ methods; secondly, if the variables are all automatically initialised at the time of object creation, you will never end up with an ‘empty’ variable (like the nil value returned when we tried to display the name of someotherdog in the previous program).
Finally, I have created a method called to_s which is intended to return a string representation of a Treasure object. The method name, to_s, is not arbitrary. The same method name is used throughout the standard Ruby object hierarchy. In fact, the to_s method is defined for the Object class itself which is the ultimate ancestor of all other classes in Ruby. By redefining the to_s method, I have added new behaviour which is more appropriate to the Treasure class than the default method. In other words, I have ‘overridden’ its to_s method.
The new method creates an object so it can be thought of as the object’s ‘construc-tor’. However, you should not normally implement your own version of the new method (this is possible but it is generally not advisable). Instead, when you want to perform any ‘setup’ actions – such as assigning values to an object’s internal variables - you should do so in a method named initialize. Ruby ex-ecutes the initialize method immediately after a new object is created.
Garbage Collection
In many languages such as C++ and Delphi for Win32, it is the pro-grammer’s responsibility to destroy any object that has been created when it is no longer required. In other words, objects are given de-structors as well as constructors. In Ruby, you don’t have to do this since Ruby has a built-in ‘garbage collector’ which automatically de-stroys objects and reclaims the memory they used when they are no longer referenced in your program.