26 July 2007
andMemoization 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.
26 July 2007
andMemoization 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.
# 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
original = "__unmemoized_ __"
# 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