# Cached proc?

**URL:** <https://www.ruby-forum.com/t/cached-proc/94748>\
**Category:** Ruby\
**Created:** [May 12, 2006, 7:16pm UTC](https://www.ruby-forum.com/t/cached-proc/94748 "2006-05-12T19:16:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dasch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b2d939/32.png) [@dasch](https://www.ruby-forum.com/u/dasch)\
**Post date:** [May 12, 2006, 7:16pm UTC](https://www.ruby-forum.com/t/cached-proc/94748/1 "2006-05-12T19:16:34Z")

</div>

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 🙂

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

---

<div class="post-metadata">

**Author:** ![dasch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b2d939/32.png) [@dasch](https://www.ruby-forum.com/u/dasch)\
**Post date:** [May 12, 2006, 7:22pm UTC](https://www.ruby-forum.com/t/cached-proc/94748/2 "2006-05-12T19:22:49Z")

</div>

Daniel S. wrote:

> def cached\_proc(&block)

That should of course read

def cached\_proc(&block)  
CachedProc.new(&block)  
end

Stupid me…
