Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.