Created
March 3, 2013 16:17
-
-
Save taiki45/5076719 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Memoize | |
def memoize(*names) | |
names.each do |name| | |
target = instance_method(name) | |
wrapped = lambda do |arg| | |
@_cache_ ||= {} | |
@_cache_[name] ||= {} | |
@_cache_[name][arg] || @_cache_[name][arg] = target.bind(self).call(arg) | |
end | |
define_method name, &wrapped | |
end | |
end | |
end | |
# Usage | |
class Foo | |
extend Memoize | |
def fib(n) | |
n <= 1 ? 1 : fib(n -1) + fib(n - 2) | |
end | |
def fib2(n) | |
n <= 1 ? 1 : fib2(n - 1) + fib2(n - 2) | |
end | |
memoize :fib2 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment