Skip to content

Instantly share code, notes, and snippets.

@cassiano
Created June 13, 2012 12:14
Show Gist options
  • Select an option

  • Save cassiano/2923694 to your computer and use it in GitHub Desktop.

Select an option

Save cassiano/2923694 to your computer and use it in GitHub Desktop.
Memoization with and without context
# Original idea probably due to Robert Feldt
module Memoize
def remember(name, options = {})
memory = {}
original_method = instance_method(name)
define_method(name) do |*args|
lookup = options[:context] ? (memory[self] ||= {}) : memory
if lookup.has_key?(args)
lookup[args]
else
original = original_method.bind(self)
lookup[args] = original.call(*args)
end
end
end
end
class Discounter
extend Memoize
def discount(*skus)
expensive_discount_calculation(*skus)
end
alias_method :discount2, :discount
remember :discount
remember :discount2, :context => true
private
def expensive_discount_calculation(*skus)
puts "Expensive calculation for #{skus.inspect}"
skus.inject {|m,n| m + n }
end
end
puts '------- discount ---------'
puts 'Using d:'
d = Discounter.new
puts d.discount(1,2,3)
puts d.discount(1,2,3)
puts d.discount(2,3,4)
puts d.discount(2,3,4)
puts 'Now using e:'
e = Discounter.new
puts e.discount(1,2,3)
puts e.discount(1,2,3)
puts e.discount(2,3,4)
puts e.discount(2,3,4)
puts '------- discount2 ---------'
puts 'Using d:'
d = Discounter.new
puts d.discount2(1,2,3)
puts d.discount2(1,2,3)
puts d.discount2(2,3,4)
puts d.discount2(2,3,4)
puts 'Now using e:'
e = Discounter.new
puts e.discount2(1,2,3)
puts e.discount2(1,2,3)
puts e.discount2(2,3,4)
puts e.discount2(2,3,4)
@cassiano

Copy link
Copy Markdown
Author

------- discount ---------
Using d:
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9
Now using e:
6
6
9
9
------- discount2 ---------
Using d:
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9
Now using e:
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment