Skip to content

Instantly share code, notes, and snippets.

@trajing
Created November 14, 2015 23:15
Show Gist options
  • Save trajing/cec69ec50a8767a97b6d to your computer and use it in GitHub Desktop.
Save trajing/cec69ec50a8767a97b6d to your computer and use it in GitHub Desktop.
Ruby Simple Memoization
# Play with this at https://eval.in/468799
class Memoizer
class MemoEmpty; end
def initialize(proc = nil, &block) # I should write something to make this easier as well.
@marker == MemoEmpty.new
@cache = {}
@cache.default = @marker
if block_given?
@block = block
elsif proc
@block = proc
else
raise ArgumentError, 'must give proc or block'
end
end
def call(*args)
if @cache[args].object_id == @marker.object_id
@cache[args] = @block[*args]
end
@cache[args]
end
alias_method :[], :call
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment