From: Robert Dober Date: 2010-04-14T21:38:47+09:00 Subject: Re: Memoize and GC 2010/4/13 Jesús Gabriel y Galán : > On Tue, Apr 13, 2010 at 6:26 PM, Intransition wrote: >> I have a quick question. I just re-read: >> >>  http://www.engineyard.com/blog/2010/memoization-and-id2ref/ >> >> I am wondering about garbage collection. Am I right to think that >> using >> >>  def foo >>    @foo ||= something >>  end >> >> will mean that @foo be GC'd when the object is GC'd, but if I do >> >>  FOO = [] >> >>  def foo >>    FOO[object_id] ||= something >>  end >> >> Then the memorized entry will just hang around forever? >> >> If so, then how do we do it without polluting the instance var space >> (as in example 2), but still get the garbage collection (as in example >> 1)? >> >> Thanks. >> >> > > One way could be using a closure that redefines the method: > > irb(main):019:0> class A > irb(main):020:1> def a > irb(main):021:2> puts "expensive calculation of a..." > irb(main):022:2> a = "complex value" > irb(main):023:2> self.class.send(:define_method, :a) do I like the closure idea, but I guess the memozing got lost a little bit ;). thus I would write def a _a = nil self.class.module_eval do define_method :a do _a ||= "expensive calculation" end define_method :_invalidate_a do _a = nil end end a end Cheers R. -- Learning without thought is labor lost; thought without learning is perilous.” --- Confucius