Skip to content

Instantly share code, notes, and snippets.

@henrik
Created January 26, 2012 10:23
Show Gist options
  • Save henrik/1682121 to your computer and use it in GitHub Desktop.
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.
def my_method(foo, bar)
memoize(:my_method, foo, bar) do
foo * bar
end
end
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