Alex Young
3/24/2007 4:04:00 PM
jeff_alexander_44@yahoo.com wrote:
> def scope(*args)
> yield(*args)
> end
>
> scope(Array.new) { |array|
> array.push 1
> array.push 7
> array.push 11
> puts array.join(",")
> }
> # here the variable 'array' is gone -- is it deallocated?
No. In general, it won't be deallocated until the next GC pass.
> I am interested in using ruby for some resource-intensive tasks. In
> the above example, imagine Array replaced with some resource-tied
> class written in C, for example a set of hardware textures.
>
> Does ruby make a special effort to release a variable when it goes out
> of scope? The canonical example is
>
> File.open("foo.txt") { |f|
> print f.read
> }
> # internal file handle released here
>
> Is this behavior a general rule, or just a special case for
> File.open()?
The release of a file handle is a different case to freeing a variable.
You might be thinking of the release of a file handle as being handled
by a destructor - that's not what's happening. Ruby doesn't have
destructors. It does have finalizers, but they aren't the same (mainly
because they're not guaranteed to be called, although I'll have to defer
to someone more knowledgeable than myself as to the details). In
essence, as I understand it File.open with a block does something
equivalent to this (very)pseudocode:
class File
def open(filename, mode)
file_handle = fopen(filename, mode)
yield(File.create_from_handle(file_handle))
fclose(file_handle)
end
end
> And is it released immediately or upon the
> next GC pass?
It's released immediately, but that's as a consequence of the code in
File.open rather than because it's gone out of the block's scope.
Hope this helps,
--
Alex