Ondřej Želazko
Ondřej Želazko

Reputation: 659

Using class as a key for a hash?

I've just realized that I am using class type as a key for a hash variable: (not this exactly)

def add_to_cache(obj)
  @cache[obj.class] = [] unless @cache.has_key? obj.class
  @cache[obj.class] << obj
end

So I am curious if anyone can explain it. Is there some downside? How is it stored in memory? Should I convert it (obj.class) into Symbol or String rather?

Upvotes: 3

Views: 274

Answers (2)

sawa
sawa

Reputation: 168091

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

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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.

Upvotes: 4

Related Questions