From: Warren Brown Date: 2003-06-10T05:22:46+09:00 Subject: Re: array.uniq does not use == ? Orion, > My Agent is an object I wish to use in a genetic > algorithm. Among other things, it has attributes > chromosome and fitness. I have "mixed in" the > Comparable module and defined my <=> operator so > I can sort my Agents based on their level of > fitness. > > However, I wish to grab "unique" agents based on > their chromosomes as well. The way Array#uniq works is basically: class Array def uniq tmphash = {} self.each { |e| tmphash[e] = true } return self.dup if self.length == tmphash.length tmparray = [] self.each { |e| tmparray << e if tmphash.delete(e)} tmparray end end This means that you will want to override Agent#hash. About the only requirement for a hash key is that it must respond to #hash with a value that does not change. See the Pickaxe book (The Ruby Language/The Basic Types/Requirements for a Hash Key) for more information. You could probably get away with hash returning "#{@chromosome}:#{@fitness}". In addition to adding Agent#hash, you will want to override Agent#eql? to assert your definition of equality when comparing for uniqueness. I hope this helps. - Warren Brown