From: "Florian Groß" Date: 2005-11-09T23:59:36+09:00 Subject: Re: memoize and yaml Brian Buckley wrote: >>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 > > Two questions of this solution. (It works and is what I need now so > I'm just looking to round out Ruby skills.) > > 1 Why is the 'remove_method(name)' line necessary? Does not the next > define_method call get rid of the method anyway by overriding? Overriding methods usually produces warnings. It's best to remove the methods first. > 2 The module requires use of 'extend' instead of 'include'. Is there > a comparable 'include' solution, and (if there is) would it be > preferred because, for example, one could not use this solution on a > class that already extends something else? Actually, I think this is the cleanest solution. In theory you could also offer a custom append_features() which defines the methods on the class or module including Memoize itself. That's more complex and not as easy to understand, though, in my opinion.