On Tue, Jul 13, 2010 at 11:40 AM, Bruno A <sardaukar.siet / gmail.com> wrote:
> On 13-07-2010 17:30, Abder-Rahman Ali wrote:
>> In the "Why's poignant guide to Ruby" book, it states the following:
>>
>> "If you can't get to an object through a variable, then Ruby will figure
>> you are done with it and will get rid of it. Periodically, Ruby sends
>> out its garbage collector to set these objects free."
>>
>> The point I'm not getting here is: "If you can't get to an object
>> through a variable..."
>>
>> Can you provide an examples that illustrates this?
>>
>> Thanks.
>
> a = [1,2,3].find {|x| x > 3}
>
> puts a
>
>
> In this (maybe too simple) example, x is garbage-collected once flow
> leaves the block.
>

Actually this is a bad example for several reasons.

1) variables don't get collected, object do.
http://talklikeaduck.denhaven2.com/2006/09/13/on-variables-values-and-objects

  In this example x is a variable which over the course of execution
gets assigned to reference 1, then 2, then 3.

2) FixNums which are the only class of object assigned to x in this
example are never garbage collected, since they are immediate values.

Now what does GC really do?  What it really does is make sure that any
object which can still be reached via a chain of references starting
with a root set of references WON"T be freed and reused before they
should be.  This is really the primary job of a GC, the secondary job,
which most people think of what a GC does, is to allow the resources
used by objects which be provedn to be no longer be reachable from
that root set to be reused.

The root set comprised references such as:

Any constants in the outermost name space,  (e.g. the object which is
referenced by say Array)
Any references currently on the activation stack of running threads.
These references will be things like method invocation parameter
values, local temporary variable values, and block argument values.

The reachable objects are those referenced by any reference in the
root set, any object referenced by any of the variables within those
objects etc. etc.

The effect of a variable going out of scope (e.g. a temporary on the
invocation frame of a method which has returned), is that that
reference is no longer part of the root set. but if there is at least
one other reference to the object in question reachable from somewhere
else in the root set then that object WILL NOT be reclaimed by a
bug-free garbage collector.


-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: http://github.com/rubyredrick
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale