Created
January 28, 2025 05:24
-
-
Save hmaddocks/ef30458cf2cff8c38fb4d29f3908682b to your computer and use it in GitHub Desktop.
A simple Ruby memoization/cache class
This file contains 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 Memo | |
def initialize | |
@mutex = Mutex.new | |
@values = {} | |
end | |
def memoize(key = :_default_key) | |
raise ArgumentError, "Block is required" unless block_given? | |
@mutex.synchronize do | |
if @values.key?(key) | |
@values[key] | |
else | |
@values[key] = yield | |
end | |
end | |
end | |
def clear(key = nil) | |
@mutex.synchronize do | |
if key | |
@values.delete(key) | |
else | |
@values.clear | |
end | |
end | |
nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment