From: Nat Pryce Date: 2001-09-07T20:34:57+09:00 Subject: [ruby-talk:20978] Re: destructor Ruby uses blocks to scope resource allocation and deallocation to scopes , just like C++ does with constructors/destructors. Look at the File::open method for an example. The basic idiom is for the class to define a method that takes a block, create an instance, pass it to the block, and then destroy the instance with an ensure statement. Here's some pseudocode illustrating this idiom in the abstract... class Resource def Resource.use( param ) resource = Resource.new( param ) try return yield( resource ) ensure resource.close end end end ----- Original Message ----- From: "Niklas Frykholm" To: "ruby-talk ML" Sent: Friday, September 07, 2001 11:46 AM Subject: [ruby-talk:20977] Re: destructor > [Frank Sonnemans] > > Does Ruby have a destructor as in C++? > > Not like that in C++. Since Ruby frees all memory automatic through its > garbage collection, it does not need destructors. > > You can use ObjectSpace.define_finalizer to define a method that will be called > when an object is garbage collected. That is somewhat similar to a destructor, > but note that there can be a long delay between your last use of the object and > the start of garbage collection -- that may not be what you want. > > In some cases, it is better to define a method that does what you want > (i.e. File.close) than to do it automatically in a finalizer. > > // Niklas > >