Created
March 1, 2018 20:57
-
-
Save soulcutter/57938277aea34a343128a86218c85692 to your computer and use it in GitHub Desktop.
A memory-leaking memoization implemenation inspired by https://twitter.com/PragTob/status/969292754294583297
This file contains hidden or 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 Memo | |
def memoize(method_name) | |
original_method = instance_method(method_name) | |
method_cache = Hash.new { |h, k| h[k] = {} } | |
define_method(method_name) do |*args, &block| | |
if method_cache[self].key?([args, block]) | |
method_cache[self][[args, block]] | |
else | |
method_cache[self][[args, block]] = original_method.bind(self).call(*args, &block) | |
end | |
end | |
end | |
end | |
class Count | |
FOO = (1..Float::INFINITY).each.lazy | |
def count | |
FOO.next | |
end | |
extend Memo | |
memoize :count | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment