Skip to content

Instantly share code, notes, and snippets.

@cjbottaro
Last active November 18, 2016 19:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjbottaro/9163450 to your computer and use it in GitHub Desktop.
Save cjbottaro/9163450 to your computer and use it in GitHub Desktop.
Memoizing in Ruby 2 with prepend
module Memoizable
def self.extended(mod)
mod.module_eval{ prepend(@memoizer = Module.new) }
end
def memoize(name)
@memoizer.module_eval do
define_method(name) do |*args, &block|
raise(ArgumentError, "cannot memoize method called with block") if block
@memoized ||= {}
@memoized[name] ||= {}
if @memoized[name].has_key?(args)
@memoized[name][args]
else
@memoized[name][args] = super(*args, &block)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment