Created
January 26, 2012 10:23
-
-
Save henrik/1682121 to your computer and use it in GitHub Desktop.
Simple memoize method for Ruby now that ActiveSupport::Memoizable is deprecated. Memoizes per argument set, handles falsy values.
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
def my_method(foo, bar) | |
memoize(:my_method, foo, bar) do | |
foo * bar | |
end | |
end |
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
def memoize(name, *args) | |
@memoizations ||= {} | |
@memoizations[name] ||= {} | |
if @memoizations[name].has_key?(args) | |
@memoizations[name][args] | |
else | |
@memoizations[name][args] = yield | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment