From: ara.t.howard@... Date: 2006-01-01T10:28:17+09:00 Subject: Re: Memoization, files and Marshal? On Sun, 1 Jan 2006, Daniel Berger wrote: > Hi all, > > Inspired by a recent blog entry by Mauricio Fernandez, I decided to try > to add a method to the memoize package that would allow users to > memoize using a file based approach rather than memory, either to > conserve memory or for persistance. > > However, I'm not sure it's possible. If it is, I'd love to know how. > If it's not, well, pstore it is. > > Here's what I tried: > > def memoize_to_file(name, file) > meth = method(name) > cache = Hash.new.update(Marshal.load(File.read(file))) rescue nil > cache ||= {} > (class << self; self; end).class_eval do > define_method(name) do |*args| > if cache.has_key?(args) > cache[args] > else > cache[args] ||= meth.call(*args) > File.open(file, "wb+"){ |f| Marshal.dump(cache, f) } > end > end > end > cache > end > > # Code snippet > include Memoize > def fib(n) > return n if n < 2 > fib(n-1) + fib(n-2) > end > memoize_to_file(:fib, "temp.txt") > fib(10) > > However, running that gives me this error: in `fib': undefined method > `+' for # (NoMethodError) > > Any ideas? > > Thanks, harp:~ > cat a.rb def memoize_to_file(name, file) cache = Hash.new.update(Marshal.load(File.read(file))) rescue {} (class << self; self; end).class_eval do define_method(name) do |*args| unless cache.has_key?(args) cache[args] = method(name).call(*args) File.open(file, "wb+"){|f| Marshal.dump(cache, f) } end cache[args] end end end def fib(n) return n if n < 2 fib(n-1) + fib(n-2) end memoize_to_file "fib", "fib.cache" n = fib 10 p n harp:~ > ruby a.rb 55 regards. -a -- =============================================================================== | ara [dot] t [dot] howard [at] noaa [dot] gov | all happiness comes from the desire for others to be happy. all misery | comes from the desire for oneself to be happy. | -- bodhicaryavatara ===============================================================================