Skip to content

Instantly share code, notes, and snippets.

@hmaddocks
Created January 28, 2025 05:24
Show Gist options
  • Save hmaddocks/ef30458cf2cff8c38fb4d29f3908682b to your computer and use it in GitHub Desktop.
Save hmaddocks/ef30458cf2cff8c38fb4d29f3908682b to your computer and use it in GitHub Desktop.
A simple Ruby memoization/cache class
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