From: "Jesús Gabriel y Galán" Date: 2010-04-14T01:49:36+09:00 Subject: Re: Memoize and GC 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 irb(main):024:3* a irb(main):025:3> end irb(main):026:2> a irb(main):027:2> end irb(main):028:1> end => nil irb(main):029:0> obj = A.new => # irb(main):030:0> obj.a expensive calculation of a... => "complex value" irb(main):031:0> obj.a => "complex value" Jesus.