Destructor?

Hi!

I came across a problem, while being interested in a ruby-cpp project:
can I somehow get a ruby object from ruby destruct?

So how can I explicitly free an object? There is no destructor in ruby,
is there?

Gergo

···


±[ Kontra, Gergelykgergely@mcl.hu PhD student Room IB113 ]---------+

http://www.mcl.hu/~kgergely “Olyan langesz vagyok, hogy |
Mobil:(+36 20) 356 9656 ICQ: 175564914 poroltoval kellene jarnom” |
±- Magyar php mirror es magyar php dokumentacio: http://hu.php.net --+

“Gergely Kontra” kgergely@mcl.hu schrieb im Newsbeitrag
news:20040304093051.GA20779@mlabdial.hit.bme.hu…

Hi!

I came across a problem, while being interested in a ruby-cpp project:
can I somehow get a ruby object from ruby destruct?

So how can I explicitly free an object? There is no destructor in ruby,
is there?

Nope. The typical idiom is to use blocks with ensure:

a = some_initialization
begin

a.do_work

ensure
a.close
end

Or, encapsulated in a method:

File.open(“foo.txt”) do |io|
while ( line = io.gets )
print line
end
end

File.open() then looks like this:

def open(name, mode=“r”)
io = create_file_io_somehow( name, mode )
begin
yield io
ensure
io.close
end
end

(I omitted the non block variant for better readability.)

For completeness reasons let me mention that there are finalizers, but
they don’t have the same properties as constructors of C++, the most
striking difference beeing that you can’t control the point in time when
they are called. See:

http://www.rubycentral.com/book/ref_m_objectspace.html#ObjectSpace.define_finalizer

Regards

robert

Another less obvious (and very important) difference between C++
destructors and Ruby finalizers:

  • C++ destructors are called as the object is being destructed (member
    variables are still accessible from the destructor), but
  • Ruby finalizers are called after the object is destroyed (so the
    object is no longer around and if the object has resources that need
    to be cleaned up, the finalizer must hold a reference to them).

See also:

http://www.rubygarden.org/ruby?RubyIdioms
http://www.rubygarden.org/ruby?ObjectsNotGetFinalized
http://www.rubygarden.org/ruby?DiscussionOnUsingFinalizers
http://www.rubygarden.org/ruby?RubyFromCpp

Paul

···

On Thu, Mar 04, 2004 at 10:04:42PM +0900, Robert Klemme wrote:

For completeness reasons let me mention that there are finalizers, but
they don’t have the same properties as constructors of C++, the most
striking difference beeing that you can’t control the point in time when
they are called. See:

http://www.rubycentral.com/book/ref_m_objectspace.html#ObjectSpace.define_finalizer