Essentially three things happen when you instantiate a class in Ruby:
- Space is allocated for the new object of the class to be created.
- An initializer is called to set up intsance variables, for example.
- An instance of the created object of the class is returned.
A good way to demonstrate this would be through an example. So let’s say we have a class
Country that we want to instantiate, but instead of going the usual route and doing something like
Country.new, we’ll implement our own version of
new to mimic what
new does under the hood.
fresh is what we’ll call our version of
Our implementation would then look something like this:
The documentation for
Allocates space for a new object of class’s class and does not call initialize on the new instance. The returned object must be an instance of class.
This appears to be the most important step in the instantiation process. Knowing that you can hack object instantiation presents a whole set of possibilities that amplify the dynamism of the Ruby programming language.