From: Joel VanderWerf Date: 2010-07-14T07:09:34+09:00 Subject: Re: Ruby garabage collector 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? Here's an example to play with: class C; end def make_one $c = C.new nil # Can you guess why this is here? end def clear! $c = nil end # How many reachable C instances are there? # (Note: works in MRI, but maybe not others, such as jruby) def how_many? p ObjectSpace.each_object(C) {} end GC.start how_many? # => 0 make_one how_many? # => 1 make_one how_many? # => 2 clear! how_many? # => 2 GC.start how_many? # => 0 ----- As Rick pointed out ("variables don't get collected, objects do"), the question of variable scope is not really the important one. In the above example, $c is always in scope, because it is a global. What's important is whether an object can be reached from the value assigned to $c.