Skip to content

Instantly share code, notes, and snippets.

@soulcutter
Created March 1, 2018 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soulcutter/57938277aea34a343128a86218c85692 to your computer and use it in GitHub Desktop.
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
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