Our Daily Method #3: Hash.multi
Geplaatst door Remco van 't Veer do, 07 feb 2008 08:00:00 GMT
You have probably used it before; Hash.new
with a block to make a two-dimensional hash;
map = Hash.new{|h,k| h[k] = {}}
map[:dragon][:strength] = 9
But sometimes you need a multi-dimensional hash;
def Hash.multi
Hash.new{|h,k| h[k] = Hash.multi}
end
I use it in an application to construct a simple cache with complex keys;
CACHE = Hash.multi
def expensive_query(key)
cache = CACHE[:query][auth_level][current_channel]
unless cache.has_key?(key)
cache[key] = Server.query(auth_level, current_channel, key)
else
cache[key]
end
end