After having read http://www.seejohncode.com/2012/03/16/ruby-class-allocate/ and looking more into the allocate method: http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-allocate I became very curious.
Ruby was built in a way that we did not have to manually allocate or free space for/with objects, but we are given the ability to do so. Why?
What are the uses in Ruby of allocating Objects manually? The article I read showed a custom initialize method, but are the uses of it so limited?
The main reason
allocateexists is to allow you to build custom constructors for your objects. As the article you linked mentioned, you can envision theSomeClass.newmethod as doing something like the following by default:Despite what the documentation says, the existence of the
allocatemethod is not so much about memory management as it is about providing some finer grained control over the object creation lifecycle. Most of the time, you won’t need this feature, but it is useful for certain edge cases.For example, in the Newman mail framework, I used this technique to implement a fake constructor for a TestMailer object; it implemented the
newmethod for API compatibility, but actually returned a single instance regardless of how many times it was called:I’ve not seen many other use cases apart from redefining
newas shown above (although I imagine that some weird serialization stuff also uses this feature). But with that in mind, it’s worth pointing out that Ruby consistently provides these kinds of extension points, regardless of whether or not you’ll need to use them regularly. Robert Klemme has a great article called The Complete Class which I strongly recommend reading if you want to see just how far this design concept has been taken in Ruby 🙂