Skip to content

Instantly share code, notes, and snippets.

@psstoev
Created Nov 18, 2013
Embed
What would you like to do?
Memoize solutions
# Solution 1:
class Memoizer < BasicObject
def initialize(instance)
@instance = instance
@cache = {}
end
def cache(method, *args)
@cache["#{method}, #{args}"] = @instance.public_send method, *args
end
def memoize(method, *args)
@cache["#{method}, #{args}"] || cache(method, *args)
end
def method_missing(method, *args, &block)
if ::Kernel.send :block_given?
return @instance.public_send method, *args, &block
else
memoize method, *args
end
end
private :cache, :memoize
end
# Solution 2:
class Memoizer < BasicObject
def initialize(target)
@target = target
@cache = {}
end
def method_missing(method, *args, &block)
if @target.respond_to? method
key = "#{method}, #{args}"
return @cache[key] if @cache.has_key? key
value = @target.public_send method, *args, &block
block.nil? ? @cache[key] = value : value
else
::Kernel.raise ::NoMethodError
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment