From: Sean O'Halpin Date: 2005-10-18T06:51:28+09:00 Subject: Re: declaratively caching results of a method On 10/17/05, Sean O'Halpin wrote: > On 10/17/05, Daniel Berger wrote: > > Jeff Wood wrote: > > > if you look at the examples ... normally you include the Memoize > > > functionality in your class > > > > > > class Foo > > > include Memoize > > > > > > def calc1( *args ) > > > # do something here > > > end > > > > > > memoize :calc1 > > > end > > > > > > f = Foo.new > > > f.calc1( 1,2,3 ) > > > f.calc1( 1,2,3 ) > > > f.calc1( 7,8,9 ) > > > > This won't work: "undefined method `memoize' for Foo:Class > > (NoMethodError)" > > Here's one way to do it: > > class Foo > include Memoize > def initialize > memoize :foo > end > def foo(*args) > puts "calculating foo(#{args.map{|x| x.inspect}.join(',')})" > args.inject(0) {|sum, x| sum + x} > end > end > > f = Foo.new > puts f.foo(2) > puts f.foo(2) > __END__ > calculating foo(2) > 2 > > Regards, > > Sean > I should have pointed out that this method only memoizes within the instance... Another instance of Foo won't get the benefit of the memoization. Sean