Skip to content

Instantly share code, notes, and snippets.

@vnegrisolo
Created February 3, 2017 21:52
Show Gist options
  • Save vnegrisolo/eeef6eb0341f5c276d802cc87e5921b2 to your computer and use it in GitHub Desktop.
Save vnegrisolo/eeef6eb0341f5c276d802cc87e5921b2 to your computer and use it in GitHub Desktop.
ruby-memoizer.rb
module Memoizable
module ClassMethods
@@memoizable = Hash.new
def memoize(method_name, &block)
define_method(method_name) do |*args|
puts @@memoizable
@@memoizable["#{self.class.name}|#{method_name}|#{args}"] ||= block.call(*args)
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
class Calculator
include Memoizable
memoize :sum do |a, b|
a + b
end
end
Calculator.new.sum(4,5)
Calculator.new.sum(1,3)
Calculator.new.sum(4,5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment