Created
February 3, 2017 21:52
-
-
Save vnegrisolo/eeef6eb0341f5c276d802cc87e5921b2 to your computer and use it in GitHub Desktop.
ruby-memoizer.rb
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 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