Created
November 17, 2009 17:35
-
-
Save santosh79/237086 to your computer and use it in GitHub Desktop.
Memoization by module mixin
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 remember(method) | |
orig_method_name = "_original_#{method.to_s}_" | |
alias_method orig_method_name.to_sym, method | |
define_method(method) do |*args| | |
@memory ||= {} | |
@memory[args] = send(orig_method_name,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