Created
November 19, 2011 17:35
-
-
Save steveburkett/1379104 to your computer and use it in GitHub Desktop.
Memoize. this was fun. learned a lot.
This file contains hidden or 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
#adapted from Dave Thomas's screencast on metaprogramming in Ruby | |
module Memoize | |
def remember(name, &block) | |
define_method(name, &block) | |
orig = instance_method(name) | |
mem = {} | |
define_method(name) do |*args| | |
if mem.has_key?(args) | |
mem[args] | |
else | |
bound = orig.bind(self) | |
mem[args] = bound.call(*args) | |
end | |
end | |
end | |
end | |
class Finder | |
extend Memoize | |
remember :find do |*objs| | |
expensive(*objs) | |
end | |
def expensive(*objs) | |
puts "expensive" | |
objs.inject{|m,n| m + n } | |
end | |
end | |
#test it | |
d = Finder.new | |
puts d.find(1,2,3) | |
puts d.find(1,2,3) #expensive is not called here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment