Alex Combas wrote:
>...


> Yikes! This is definitly something I'm going to need to learn to use, and use
> as often as possible. So anywho, took a quick peek at memoize.rb and was
> again just blown away but this time because the entire file was only 39 lines
> of code including white space! How can this be?
> 
> Unfortuantely, there are no comments to be had, so I was wondering
> if someone would be so kind as to reply with inserted comments in the code,
> (yes I know ruby is supposed to be readable, but im new, ok? :-)
> Just as a precaution so that I don't make any weird assumptions,
> something I'm prone to do. This would be greatly appreciated.

Basically, the arguments to the target method are used as a hash key 
into a cache. The cache hash is stored either in memory, or (optionally) 
on disk.

If you give memoize a file name it will serialize the results cache to 
and from disk using Ruby's Marshal code.

Otherwise, the cache just sits in memory.

The code defines a singleton method of the same name as the target 
method. Calls to the target method are passed to this singleton method; 
it has first crack at looking to see if there is a cached value.

If it has the value, then it is returned; all done.

Otherwise, the value is obtained by calling the original method defined 
in the class source code, the results are cached (and the file updated, 
if defined) and the value returned.

The neat part is the use of a singleton method to intercept calls to the 
target method:

class Foo

   include Memoize

   def initialize
     memoize :baz
   end

   def baz val
     "Baz sez #{val}"
   end

end

When you call

  foo = Foo.new
  foo.baz( 'Hey.' )

the first baz invoked is the singleton method defined on foo.  If it 
does not have a cached value, it calls the baz method defined in the Foo 
class.

  puts foo.singleton_methods # baz


(But note that an in-memory hash will exist for each instance.  A file 
allows for all instances to share values, and to have those values 
persist from runs of the application, but may introduce race conditions.)

-- 
James Britt

"Blanket statements are over-rated"