destructor?

G

Gergely Kontra

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
 
R

Robert Klemme

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
 
P

Paul Brannan

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,143
Messages
2,570,822
Members
47,368
Latest member
michaelsmithh

Latest Threads

Top