Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created February 8, 2013 00:26
Show Gist options
  • Save practicingruby/4735526 to your computer and use it in GitHub Desktop.
Save practicingruby/4735526 to your computer and use it in GitHub Desktop.
module Cached
def cache(*method_names)
method_names.each do |m|
original = instance_method(m)
results = {}
define_method(m) do |*a|
results[[m, a]] ||= original.bind(self).call(*a)
end
end
end
end
## EXAMPLE USAGE:
class Numbers
extend Cached
def fib(n)
raise ArgumentError if n < 0
return n if n < 2
fib(n - 1) + fib(n - 2)
end
cache :fib
end
n = Numbers.new
(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