Created
November 17, 2009 06:12
-
-
Save santosh79/236691 to your computer and use it in GitHub Desktop.
memoization with sub-class
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
class Discounter | |
def discount(*skus) | |
expensive_calc(skus) | |
end | |
private | |
def expensive_calc(*skus) | |
puts "in expensive calc for #{skus}" | |
skus.inject{|m,n| m + n} | |
end | |
end | |
class MemoDiscounter < Discounter | |
def discount(*skus) | |
@memory ||= {} | |
@memory[skus] = super unless @memory.has_key?(skus) | |
@memory[skus] | |
end | |
end | |
d = MemoDiscounter.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