From: Jeff Wood Date: 2005-10-18T04:07:31+09:00 Subject: Re: declaratively caching results of a method 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 ) ... it's a mixin, the functionality becomes a part of the functionality of the class, wrapping calls to self with the individual object it was included from. hope that makes sense. j. On 10/17/05, Brian Buckley wrote: > > You could check out Daniel Berger's memoize (based on Nobu Nokada's > > original I think) on RAA (http://raa.ruby-lang.org/project/memoize/). > > Thank you and wowser! memoize seems to do just what I'd been looking > to do. A handful of lines. I can see it works. > > #my test code > f = Foo.new > f.memoize(:calc1) > f.memoize(:calc2) > f.calc1(1,2,3) > f.calc1(1,2,3) #yep its working > f.calc1(7,8,9) #yep its working > > If I can ask a Ruby 101 question about it... Isn't "cache" in the > module (pasted below in its entirety it is so short) only a local > variable? Why does is retain state? How can one, for example, access > the cache to see the state of the cache? > > Thanks! > > --Brian > > module Memoize > MEMOIZE_VERSION = "1.0.0" > def memoize(name) > meth = method(name) > cache = {} > (class << self; self; end).class_eval do > define_method(name) do |*args| > cache[args] ||= meth.call(*args) > end > end > end > end > > -- "http://ruby-lang.org -- do you ruby?" Jeff Wood