Skip to content

Instantly share code, notes, and snippets.

@bossiernesto
Created February 5, 2020 14:41
Show Gist options
  • Select an option

  • Save bossiernesto/9d20935c56da4095eb5963428e14e1b8 to your computer and use it in GitHub Desktop.

Select an option

Save bossiernesto/9d20935c56da4095eb5963428e14e1b8 to your computer and use it in GitHub Desktop.
module Memoization
def memoize(name)
@@lookup ||= Hash.new { |h, k| h[k] = {} }
fx = instance_method(name)
define_method(name) do |args|
return @@lookup[name][args] if @@lookup[name].include?(args)
@@lookup[name][args] = fx.bind(self).call(args)
end
end
end
class Bleh
extend Memoization
memoize def saraza(a)
2*a
end
end
a = Bleh.new
a.saraza(24)
a.class.class_variable_get(:@@lookup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment