Skip to content

Instantly share code, notes, and snippets.

@psstoev
Created November 18, 2013 17:14
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 psstoev/7531555 to your computer and use it in GitHub Desktop.
Save psstoev/7531555 to your computer and use it in GitHub Desktop.
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