Created
June 2, 2017 19:55
-
-
Save davidbalbert/39eb2446b31af0e7cab475868672797d to your computer and use it in GitHub Desktop.
memoize.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Memoize | |
| def memoize(name) | |
| m = Module.new do | |
| define_method name do |*args| | |
| return instance_variable_get("@_#{name}") if instance_variable_defined? "@_#{name}" | |
| instance_variable_set("@_#{name}", super(*args)) | |
| end | |
| end | |
| prepend m | |
| end | |
| end | |
| class Foo | |
| extend Memoize | |
| memoize def foo | |
| puts 'hi' | |
| 5 | |
| end | |
| end | |
| f = Foo.new | |
| f.foo | |
| # hi | |
| #=> 5 | |
| f.foo | |
| #=> 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment