From: Bruno A Date: 2010-07-14T18:10:07+09:00 Subject: Re: Ruby garabage collector I stand corrected. Thanks! On 14-07-2010 4:08, Ken Bloom wrote: > 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 > => # > irb(main):002:0> a=Object.new > => # > > at the end of this program, there is no longer a variable that points > (either directly or indirectly) to #, so it can be > garbage collected. > > irb(main):003:0> a=[] > => [] > irb(main):004:0> b=Object.new > => # > irb(main):005:0> a << b > => [#] > irb(main):006:0> b=Object.new > => # > irb(main):007:0> a << b > => [#, #] > irb(main):008:0> b=Object.new > => # > > 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. > > -- -- @_bruno_antunes sardaukar.siet@gmail.com http://iruel.net