Skip to content

Instantly share code, notes, and snippets.

@santosh79
Created November 17, 2009 06:22
Show Gist options
  • Save santosh79/236695 to your computer and use it in GitHub Desktop.
Save santosh79/236695 to your computer and use it in GitHub Desktop.
memoizing w/sub-class - returning a new class
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
def memoize(cls, method)
Class.new(cls) do
memory = {}
define_method(method) do |*args|
memory ||= {}
memory[args] = super unless memory.has_key?(args)
memory[args]
end
end
end
d = memoize(Discounter, :discount).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