[Note: parts of this message were removed to make it a legal post.]
Ali,
In answer to your original question... I think we got a bit side-tracked by
the mention of 'scope'.
Think of it this way:
As a program executes more and more memory is being written to. This is fine
for a while but if you're the people writing Ruby (or Java even!) you need
to think of a way of somehow stopping the program from eventually wasting
all the memory available to it; or else nobody is going to use it because it
will run out of space all the time!
What they do is look for some memory to 'reuse'. They can't just write over
any old memory because it might still be needed... BUT... suppose they knew
some memory was never going to be needed by the program again - then it can
be safely deleted (and reused). cool.
Now, the question is how do we know some memory is NEVER needed again? Well,
suppose you created an object 'x' (there is memory being used to store x),
but there is now no possible route for the program to take whereby x is
accessed again - we can mark x as 'garbage' and 'collect' back it's
associated memory for reuse.
The implementation of a garbage collector (something that notices x will
never be needed again) is more technical - and there is more than one way to
do it (watching things become out of scope is just one).
You said you were struggling with the statement:
"If you can't get to an object
through a variable..."
That's just another way of saying
'if the memory can be reused' or
'it's impossible for the program to ever need that variable again' or
'the variable (say x) is garbage'!
You have garbage collectors in Java too by the way and C# etc.. just think
of it as a bit of housekeeping that needs doing every now and again
otherwise your program would grind to a halt because there would be nowhere
left to add new objects!
It is still possible that a program can run out of memory.. did you ever see
an OutOfMemoryError in Java? the garbage collector will do it's best but if
your program is still using a load of memory it has no option but to blow up
On Tue, Jul 13, 2010 at 11:13 PM, Abder-Rahman Ali <