From: Caleb Clausen Date: 2009-09-11T09:16:19+09:00 Subject: Re: What’s the best general implementation of custom #hash methods? On 9/10/09, Shot (Piotr Szotkowski) wrote: > Hello, ruby-talk. > > What’s the best (fast, yet with relatively few cases when equal hashes > are generated for non-eql objects) way to implement a hash method? > > Is XOR-ing the hashes of an object’s instance variables (assuming that > two objects are eql if their ivars are eql) a good general approach? The drawback to this algorithm would be that if you have the same values but in different variables, they'll end up hashing the same. For example: class Pair def initialize(a,b) @a,@b=a,b end def hash @a.hash^@b.hash end end Pair.new("foo","bar").hash==Pair.new("bar","foo").hash #=>true As a practical matter, this often doesn't matter. It depends on the application and if you think this kind of situation is likely. For general purpose use, it's better to have some way of encoding the 'location' of each sub-value in the hash as well.