From: "Iñaki Baz Castillo" Date: 2011-04-15T21:50:42+09:00 Subject: Get the real object in a Hash key Hi, let's suppose this simple code in which I add internal attributes to String instances and use such String objects as Hash keys: ------------------------------------------------ h = {} k1 = "aaa" k1.instance_variable_set :@name, "Aaa-011" k2 = "bbb" k2.instance_variable_set :@name, "Bbb-268" h[k1] = "Hello" h[k2] = "Bye" ------------------------------------------------ Now I want to lookup in the hash the element whose key matches "aaa" (using String#eql?): h["aaa"] => "Hello" But I don't want just to get the key associated value ("Hello"), but also the key object itself (not the "aaa" I passed but k1 object) so I can check its @name attribute. And I need it in a very efficient way. However I've realized right now that it's not possible. The hash key doesn't store the given key as a reference to such object: ------------------------------------------- puts k1.object_id => 18140060 puts k2.object_id => 16245980 h.keys.each {|k| puts k.object_id} => 16182220 => 20359940 ------------------------------------------. I've realized of it while writting this mail, so forget the previous question. Now I have another question: -------------------- myobject = MyCustomClass.new @h = {} @h[myobject] = "lalalala" -------------------- In this case, will Ruby GC delete myobject? or will it remain alive as it has been used as a key of a hash (which is not GC'd in a supposed code)? Thanks a lot. -- Iñaki Baz Castillo