Created
January 24, 2022 14:33
-
-
Save soulcutter/fb79a919c86e684fa968b6935b2b5497 to your computer and use it in GitHub Desktop.
Memoizing in Ruby without ivars and defined?
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
class Memoizer < Module | |
def initialize(method_name) | |
define_method(method_name) do | |
super().tap do |value| | |
puts "memoizing" | |
define_singleton_method(method_name) { value } | |
end | |
end | |
end | |
end | |
module Memoize | |
def memoize(method_name) | |
prepend Memoizer.new(method_name) | |
end | |
end | |
class ProofItWorks | |
@@num = 0 | |
extend Memoize | |
def foo | |
puts "expensive" | |
@@num = @@num + 1 | |
end | |
memoize(:foo) | |
end | |
class YourThing | |
extend Memoize | |
def v | |
$1 if xml =~ /blah/ | |
end | |
memoize :v | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
could (should?) have written ProofItWorks as a test, but I was mucking around in a REPL session