Last active
November 18, 2016 19:18
-
-
Save cjbottaro/9163450 to your computer and use it in GitHub Desktop.
Memoizing in Ruby 2 with prepend
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 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