From: olczyk@... (Thaddeus L. Olczyk) Date: 2001-12-24T01:37:35+09:00 Subject: [ruby-talk:29368] Re: a better way? On Sun, 23 Dec 2001 02:08:09 GMT, HarryO wrote: >On Sun, 23 Dec 2001 12:46:10 +1100, David Alan Black wrote: > > >> class Temp >> @@save = {} >> def fahrenheit(c) >> result = @@save[self] and return result puts "Performing >> calculation...." >> @@save[self] = c * 9 / 5 + 32 >> end >> end >> >> t = Temp.new >> >> puts t.fahrenheit(100) # "Performing calculation....\n212" puts >> t.fahrenheit(100) # "212" > >As usual, I'm probably missing something obvious here, but >shouldn't the index used to access @@save be "c" rather than >"self", in both cases? You hagve to forgive Dave, he's an amateur programmer and thus misses these things. Presumably self might work, if you were interested in the caching the object's state. For example: class Temp @@save={} def initialize(tIn) @c=tIn end def PrintTemp puts @c end def fahrenheit result = @@save[@c] if result==nil then puts "New Calculation" result=@c * 9 / 5 + 32 @@save[@c]=result end return result end end 1.upto(10){ |t| T=Temp.new(t) printf("Temp=") T.PrintTemp printf("In Farenheit %d\n",T.fahrenheit) } 1.upto(10){ |t| T=Temp.new(t) printf("Temp=") T.PrintTemp printf("In Farenheit %d\n",T.fahrenheit) } 1.upto(10){ |t| T=Temp.new(t) printf("Temp=") T.PrintTemp printf("In Farenheit %d\n",T.fahrenheit) } there are a couple errors ( an initialization error, plus a error in using integers ), forgive me ruby is still new to me. In the method fahrenheit you could put self as the argument to save then the second loop would print "New Calculation". In other words, if you were going to calculate based on the object state then self would work, but using the state as an index works the more fficiently. The technique described is called memoization, a technique that I believe was invented in Lisp and mostly used in that language. It has the disadvantage that it can only be used in functions that have no side effects. The one time I've seen numbers on memoziation, Kiczales, Lopes, et al. first AOP project RG ( a image filtering system ), it preformed more poorly in all aspects. It took more lines of code ( obviously), took longer to execute, and it failed to save memory.