Concise Memoization

Doug Landauer comments on using Hash default blocks for memoization, and comments that the Memoize module could be made simpler.

I’ll take a stab. Check this:

module Memoize
  def memoize( name )
    meth = method( name )
    cache = Hash.new { |cache, args|
      cache[args] = meth.call( *args )
    }
    ( class << self ; self ; end ).class_eval do
      define_method( name ) { |*args| cache[args] }
    end
    cache
  end
end

Maybe not shorter, but I daresay a little clearer.