From: "Florian Groß" Date: 2005-11-04T05:57:34+09:00 Subject: Re: memoize and yaml Brian Buckley wrote: > I am using the "memoize" module to eliminate having to redo complex, > time-consuming calculations. It works great. However, when I yamlize > my "memoized" object off to the database and then retrieve it back, > all the memoizing is lost. [...] > > #FYI... here is the Memoize module > module Memoize > MEMOIZE_VERSION = "1.1.0" > def memoize(name) > meth = method(name) > cache = {} > (class << self; self; end).class_eval do > define_method(name) do |*args| > cache.has_key?(args) ? cache[args] : cache[args] ||= > meth.call(*args) > end > end > cache > end > end This memoize module stores the cache in a local variable that can be referenced from within the memoize method wrapper. It also memoizes the methods at the instance level meaning that after storing and loading an instance the methods won't be memoized anymore. Here's a version that stores the cache in an instance variable and that replaces the method definitions at class definition time: module Memoize def memoize(name) name = name.to_sym old_method = instance_method(name) remove_method(name) define_method(name) do |*args| @cache ||= {} signature = [name] + args if @cache.include?(signature) then @cache[signature] else @cache[signature] = old_method.bind(self).call(*args) end end end end Please note that you can use neither of these memoize() methods for memoizing methods that can take a block argument as it will be dropped. Oh, and if you call a memoized method with an argument that can't be serialized by YAML this definition will probably cause trouble.