From: Jeremy Evans Date: 2007-08-21T09:29:23+09:00 Subject: Re: How to implement a hash whose key is another hash? unknown wrote: > I understand that the key of a hash can be any object. Therefore, > I would think that the key of a hash can be another hash. If I have > the following code sequence. (I using ruby 1.8.5 (2006-08-25) [i486- > linux]) > > > require 'pp' > test ={} > test["new"=>"girl"]= 100 > test["new"=>"girl"]= 200 > pp test > > I am expecting the output to be > > {{"new"=>"girl"}=>200} > > However the output I am getting is > > {{"new"=>"girl"}=>100, > {"new"=>"girl"}=>200} > > Could some explain how to use hash key which is of type hash It's a bad idea to do what you are doing. However, if you really want to, you could try installing CICPHash (sudo gem install cicphash). It's designed to be a case insensitive hash, but it can easily be generalized to consider arbitrary sets of keys as equal. The default implementation will do what you want for this simple case: irb(main):001:0> require 'pp' => true irb(main):002:0> require 'cicphash' => true irb(main):003:0> test = CICPHash.new => {} irb(main):004:0> test["new"=>"girl"]= 100 => 100 irb(main):005:0> test["new"=>"girl"]= 200 => 200 irb(main):006:0> pp test {{"new"=>"girl"}=>200} => nil However, the default implementation won't necessarily work for hashes with multiple keys, as the order of the keys in the hash is undefined. You can change that by redefining the CICPHash#convert_key method. However, as previously mentioned, you probably shouldn't use hashes as hash keys. Jeremy -- Posted via http://www.ruby-forum.com/.