Ok, I’ll the be first to admit that I’m no OO guru. Most of my OO coding has been done in Perl for heaven’s sake. I’ve also dabbled a little in C++. Now I’m learning Ruby. Ruby has some really cool idioms and features which really make writing code easier and cleaner. Of course, not everything in Ruby has me singing it’s praises. This is another of those rants…
Basically, I’m trying to write a brain dead simple class wrapper around multiple temporary files. One feature of the class was to be that the user doesn’t have to manually delete the temp files…. basically when the class goes out of scope, I’d hook into the destructor to delete the files automagically. I know this sorta thing is doable in Perl, Java and C++. Imagine my surprise when I found out that Ruby has no destructor, just a “finalize” method which is only called during garbage collection- NOT when the object goes out of scope. As a matter of fact, Ruby doesn’t provide any way to do what I want without using closures which severely limits my class since it’s designed to be managed remotely sorta like RPC.
For a language which seems to pride itself on it’s flexibility and ability to override just about any method, not being able to hook into when the object goes out of scope is just plain lame.
Pingback: Syn Fin dot Net » Blog Archive » Multithreaded server in 5 lines? Damn.
I am having the *exact* same problem. “Going out of scope” has different meanings, so I will forgive Ruby to not do anything special for going out of scope. But when the object is garbage collected, a finalizer will be called.
This site gives an example of how to hook a finalizer to your object.
The only problem is, the finalizer proc that is called has no way of accessing the specific object that is being destroyed! You will notice that you have an object_it, and may think that you can use ObjectSpace._id2ref() to get the object, but no. _id2ref() cannot be used on an object_id passed as a parameter to a finalizer.