“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:
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).
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: