Skip to content

Instantly share code, notes, and snippets.

@kevbuchanan
Created July 13, 2015 21:07
Show Gist options
  • Save kevbuchanan/37b12d7409d01b6fc2be to your computer and use it in GitHub Desktop.
Save kevbuchanan/37b12d7409d01b6fc2be to your computer and use it in GitHub Desktop.
Ruby Memoize
module Memoize
module DefMemo
def defmemo(name, &block)
define_method(name) do |*args|
__memo__[name].fetch(args) do |key|
__memo__[name][key] = instance_exec(*args, &block)
end
end
end
end
def __memo__
@__memo__ ||= Hash.new { |h, k| h[k] = {} }
end
def self.included(klass)
klass.extend(DefMemo)
end
end
class Foo
include Memoize
attr_accessor :var
attr_accessor :truthy
defmemo :bar do |x|
var + x
end
defmemo :get do
truthy
end
end
foo = Foo.new
foo.var = 1
puts foo.bar(1) == 2
foo.var = 5
puts foo.bar(1) == 2
puts foo.bar(2) == 7
foo.truthy = false
puts foo.get == false
foo.truthy = true
puts foo.get == false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment