Forum: Ruby Cached proc?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-12 19:16
(Received via mailing list)
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
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-12 19:22
(Received via mailing list)
Daniel Schierbeck wrote:
>   def cached_proc(&block)

That should of course read

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

Stupid me...
This topic is locked and can not be replied to.