26 July 2007 Norbert Crombach and Manfred Stienstra

Memoization is a technique for speeding up your code by caching the results of method calls. In this episode Norbert shows a Ruby implementation of memoization and how you can use it.

Download episode

# Code taken from an article by James Edward Gray II
# http://blog.grayproductions.net/articles/2006/01/20/caching-and-memoization
#
# Includes a fix by Remco van 't Veer
# http://pastie.textmate.org/91998

module Memoizable
  def memoize( name, cache = Hash.new )
    original = "__unmemoized_#{name}__"

    # We used this, for clarity:
    #class_eval do
    # But actually this is better:
    ([Class, Module].include?(self.class) ? self : self.class).class_eval do
      alias_method original, name
      private      original
      define_method(name) { |*args| (cache[self] ||= {})[args] ||= send(original, *args) }
    end
  end
end