Skip to content

Instantly share code, notes, and snippets.

@bfabry
Forked from practicingruby/composed_cache.rb
Created February 8, 2013 02:02
Show Gist options
  • Save bfabry/4736038 to your computer and use it in GitHub Desktop.
Save bfabry/4736038 to your computer and use it in GitHub Desktop.
class ComposedCache
def initialize(target)
@target = target
end
def cache(*method_names)
method_names.each do |m|
original = @target.method(m)
results = {}
@target.define_singleton_method(m) do |*a|
results[[m, a]] ||= original.call(*a)
end
end
end
def method_missing(m, *a, &b)
@target.send(m, *a, &b)
end
end
class Numbers
def fib(n)
raise ArgumentError if n < 0
return n if n < 2
fib(n - 1) + fib(n - 2)
end
end
n = ComposedCache.new(Numbers.new)
n.cache(:fib)
(0..100).each { |e| p [e, n.fib(e)] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment