From: Robert Klemme Date: 2011-04-15T22:48:21+09:00 Subject: Re: Get the real object in a Hash key On Fri, Apr 15, 2011 at 3:14 PM, Iņaki Baz Castillo wrote: > 2011/4/15 Robert Klemme : >> On Fri, Apr 15, 2011 at 2:50 PM, Iņaki Baz Castillo wrote: >>> 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: >> >> This is a special optimization for unfrozen Strings as Hash keys. > > Oopss, if I freeze the string before inserting it as Hash key it > doesn't occur (I get some object_id) :) > Same occurs if I use a class inheriting from String. Good to know! > > > Then I come back to my original question: > > ---------------- > k1 = "aaa" > k1.freeze > > h = {} > > h[k1] = "HELLO" > ---------------- > > Given a string "aaa", how can I get the object k1 from the hash? (I > mean without comparing String#eql? each key with the string "aaa") > Unfortunatelly I think Hash class does not provide a method for it. Exactly. And you don't want to do it. A Hash is an associative storage which associates the value with your key. If you need to stuff in more information - you need to add it to the value and not the key. The simplest would be to define a Struct, e.g. Value = Struct.new :name, :val Then put this into the Hash as values h[k1] = Value["a name", "HELLO"] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/