Implement a Cache in Ruby:
class Cache
def initialize
@hash = {}
end
def [](key)
@hash[key]
end
def []=(key, value)
@hash[key] = value
end
end
Usage:
cache = Cache.new
if user = cache["1"]
user = cache["1"] = User.find("1")
end
user
To make it thread safe, add a Mutex to protect the class from accessing by other threads:
require "thread"
class Cache
def initialize
@mutex = Mutex.new
@hash = {}
end
def [](key)
@mutex.synchronize { @hash[key] }
end
def []=(key, value)
@mutex.synchronize { @hash[key] = value }
end
end