Cached proc?


#1

I haven’t been able to find a cached proc class in the Facets list, so I
whipped up one on my own. Pretty basic, but it’s nice to have a facet
for it :slight_smile:

class CachedProc
def initialize(&block)
@proc = block
@cache = Hash.new{|cache, args| cache[args] = @proc.call(*args) }
end

 def call(*args)
   @cache[args]
 end

 alias_method :[], :call

 def method_missing(name, *args, &block)
   @proc.send(name, *args, &block)
 end

end

def cached_proc(&block)

p = cached_proc{|x, y| puts ‘*’; x * y }
p.call(2, 3) => 6
-> *
p.call(2, 3) => 6

Cheers,
Daniel


#2

Daniel S. wrote:

def cached_proc(&block)

That should of course read

def cached_proc(&block)
CachedProc.new(&block)
end

Stupid me…