Where do you say this:
def memoize
I think you want to say this:
class Proc def memoize
This will add the public memoize method for Procs and lambda { ... } (or -> { ... } in the new Rubies), giving you a copy of Proc.
Now on memoize . Methods return the value of their last expression, and for memoize , this is the last expression:
lambda { |*args| unless cache.has_key?(args) cache[args] = self[*args] end cache [args] }
So memoize returns a wrapper for Proc ( self ), which is a closure over cache , and this whole wrapper does the following:
- See if
cache entry for the argument list in question ( args array). - If we don’t have a cached value, then calculate the original Proc value (
self[*args] ) and save it in the cache. - Returns the cached value.
You can use the [] method to execute Proc, so proc.call(a, b) same as proc[a, b] .
mu is too short
source share