Skip to content

Instantly share code, notes, and snippets.

@santosh79
Created November 17, 2009 17:37
Show Gist options
  • Save santosh79/237088 to your computer and use it in GitHub Desktop.
Save santosh79/237088 to your computer and use it in GitHub Desktop.
Memoization with method binding
module Memoize
def remember(method)
original_method = instance_method(method)
define_method(method) do |*args|
@memory ||= {}
bound_method = original_method.bind(self)
@memory[args] = bound_method.call(args) unless @memory.has_key?(args)
@memory[args]
end
end
end
class Discounter
extend Memoize
def discount(*skus)
expensive_calc(skus)
end
remember :discount
private
def expensive_calc(*skus)
puts "in expensive calc for #{skus}"
skus.inject{|m,n| m + n}
end
end
d = Discounter.new
d.discount(1,2,3)
d.discount(1,2,3)
d.discount(4,2,3)
d.discount(4,2,3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment