On 10/17/05, Brian Buckley <briankbuckley / gmail.com> wrote:
>
> If I can ask a Ruby 101 question about it...  Isn't "cache" in the
> module (pasted below in its entirety it is so short) only a local
> variable?  Why does is retain state? How can one, for example, access
> the cache to see the state of the cache?

Yes it is a local variable, but the block used in define_method is a
closure, so the cache variable is accessible from within that block.
It is done this way instead of using a instance variable or other
non-local variables because there needs to be a cache for each method
that is memoized. Since each invocation of memoize creates a new local
cache for that memoized method, each method has its own cache. It is a
very clever use of closures.

There may be some trick to access the cache, but it isn't something
that is very straightforward. This is because the block is used to
define a method, and when you try to get that block back using
"method" to access its binding, the binding is for the object in
question, not for the closure of the original block. Hope that made
sense :)

Do you *really* need to look at the cache? If you hadn't read the
source code for memoize you wouldn't realize it was there, so.......

Ryan