From: Thomas Hurst Date: 2002-02-17T04:11:11+09:00 Subject: Re: hash as key in hash * Albert Wagner (alwagner@tcac.net) wrote: > I don't understand why this doesn't work. Can anyone help? > > hash = { {'a'=> 1, 'b' => 2, 'c' =>3} => 1, {'c' => 1, 'b' => 3} => 2} > arg_hash = {'c' => 1, 'b' => 3} > p hash.key?(arg_hash) Hashes use the numeric result of the hash method call for any object used as a key: irb(main):001:0> {'c' => 1, 'b' => 3}.hash 67528232 irb(main):002:0> {'c' => 1, 'b' => 3}.hash 67514422 irb(main):003:0> {'c' => 1, 'b' => 3}.hash 67507872 You're creating new hash objects; their object ID's differ, hence their hashes differ. Instead, create one instance and use that everywhere: key1 = {'a'=> 1, 'b' => 2, 'c' => 3} key2 = {'c' => 1, 'b' => 3} hash = {key1 => 1, key2 => 2} p hash.key?(key2) Since: irb(main):001:0> bla = {'c' => 1, 'b' => 3} {"b"=>3, "c"=>1} irb(main):002:0> bla.hash 67527642 irb(main):003:0> bla.hash 67527642 irb(main):004:0> bla.hash 67527642 However, I suspect you really want to index by hash content, not hash objects. For that, something more like: hash = { {'a'=> 1, 'b' => 2, 'c' => 3}.to_str => 1, {'c' => 1, 'b' => 3}.to_str => 2} arg_hash = {'c' => 1, 'b' => 3} p hash.key?(arg_hash.to_str) Will be more like it. However, hash ordering is not guaranteed, hence to_str probably isn't either, so to be more correct you better sort it first: hash = { {'a'=> 1, 'b' => 2, 'c' => 3}.sort.to_s => 1, {'c' => 1, 'b' => 3}.sort.to_s => 2} arg_hash = {'c' => 1, 'b' => 3} p hash.key?(arg_hash.sort.to_s) You may additionaly want to .join explicitly with a seperator, since to_s provides none, so you could conceivably have two different arrays convert to the same string. After going through all this, you might want to extend the Hash class and override hash() with these calls: class HashWhichYouCanReliablyUseAsKeyInAHash < Hash def hash return sort.to_s end end And create your hash indexes by creating new instances of the new class. -- Thomas 'Freaky' Hurst - freaky@aagh.net - http://www.aagh.net/ - There's no point in being grown up if you can't be childish sometimes. -- Dr. Who