On Wed, 14 Jul 2010 00:40:05 +0900, Bruno A 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.

Nothing gets garbage collected here becuase 1,2, and 3 are value objects 
(they're special in that they're not stored on the heap, but stored in 
the memory that would be the pointer to most other objects), and because 
they're still accessible through the array (a points to an array, which 
points to each of the array's 3 elements) even after the loop ends. 

A better example is:

irb(main):001:0> a=Object.new
=> #<Object:0x7f361c5dbe58>
irb(main):002:0> a=Object.new
=> #<Object:0x7f361c5d1c50>

at the end of this program, there is no longer a variable that points 
(either directly or indirectly) to #<Object:0x7f361c5dbe58>, so it can be 
garbage collected.

irb(main):003:0> a=[]
=> []
irb(main):004:0> b=Object.new
=> #<Object:0x7f361c5c33d0>
irb(main):005:0> a << b
=> [#<Object:0x7f361c5c33d0>]
irb(main):006:0> b=Object.new
=> #<Object:0x7f361c5a9890>
irb(main):007:0> a << b
=> [#<Object:0x7f361c5c33d0>, #<Object:0x7f361c5a9890>]
irb(main):008:0> b=Object.new
=> #<Object:0x7f361c5941c0>

In this example, nothing gets garbage collected. I allocated three 
Objects, and one Array. At the end of execution, the Array is pointed to 
by a, and two of the Objects are pointed to by the Array. The third 
Object is pointed to by b.


-- 
Chanoch (Ken) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/