我刚刚意识到我正在使用类类型作为哈希变量的键:(不完全是)
def add_to_cache(obj)
@cache[obj.class] = [] unless @cache.has_key? obj.class
@cache[obj.class] << obj
end
所以我很好奇是否有人可以解释它。有什么缺点吗?它是如何存储在内存中的?我应该将它(obj.class)转换为 Symbol 还是 String?
我刚刚意识到我正在使用类类型作为哈希变量的键:(不完全是)
def add_to_cache(obj)
@cache[obj.class] = [] unless @cache.has_key? obj.class
@cache[obj.class] << obj
end
所以我很好奇是否有人可以解释它。有什么缺点吗?它是如何存储在内存中的?我应该将它(obj.class)转换为 Symbol 还是 String?
In ruby you can have any object being a key of a hash. The method hash
of the object is called for the actual hashing. I assume this method is optimized enough and good enough for Class
. Converting the class to string or symbol here is not needed.
I am guessing that your objective might be to keep track of all instances of a certain class. If that is the case, then you do not need to, and should not, cache them manually. To get all instances of class klass
, do this:
ObjectSpace.each_object(klass).to_a