From: Ben Giddings Date: 2003-07-29T11:19:28+09:00 Subject: Singletons as globals and GC Although Ruby allows the use of global variables, I still prefer not to use them. I am wary that someone else might have chosen the same variable name as me, and besides, they just don't feel properly OO. Singletons seem like the best solution to this problem, but I'm concerned about garbage collection. Say I have two classes that each do a lot of work. I instantiate one, do a bunch of calculations and return a result. I then instantiate a second class and do a bunch more work on that result. Say both classes want to use this global / singleton, and want to make sure that it doesn't get garbage collected between calls, what's the best way to do this? Example code: class Stats include Singleton def initialize @count = 0 end def sawAnother @count += 1 end end class Worker1 def doStuff @stats = Stats.instance ... end end class Worker2 def doOtherStuff @stats = Stats.instance ... end def showResult @stats.dumpStats end end w1 = Worker1.new w1.doStuff w2 = Worker2.new w2.doStuff w2.showResult What I want to avoid is having the Stats singleton get garbage collected between calls to w1.doStuff and the creation of Worker2.new. Any comments? Ben