Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class as a key for a hash?

Tags:

ruby

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?

like image 295
Ondřej Želazko Avatar asked Jun 01 '26 07:06

Ondřej Želazko


2 Answers

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.

like image 73
Ivaylo Strandjev Avatar answered Jun 02 '26 21:06

Ivaylo Strandjev


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
like image 36
sawa Avatar answered Jun 02 '26 21:06

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!