Gergely Kontra said:
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