From: Jason Creighton Date: 2003-06-28T05:32:28+09:00 Subject: Re: Using & for arrays of objects On Fri, 27 Jun 2003 09:48:56 +0900 "Krishna Dole" wrote: > Hi, > I'm having trouble using the & (intersection) method on two arrays of > objects. I know that if the objects don't have comparison methods, & won't > work because it is looking at the object IDs rather than values stored in > the objects, but I can't seem to get & to use the comparison methods I want. & uses hashes under the hood. You need to define #hash and #eql? for your object so that any object you want to be considered equal have equal hash values and eql?(other) returns true. The easiest way would be like this: class N def initialize(n) @n = n end def hash() @n.hash() end def eql?(other) @n.hash() == other.hash() end attr_reader :n end In use: >> [ N.new(1), N.new(2) ] & [ N.new(2), N.new(3) ] => [#] ~/prog/ruby$ ri Object#eql? This is a test 'ri'. Please report errors and omissions on http://www.rubygarden.org/ruby?RIOnePointEight ------------------------------------------------------------ Object#eql? obj.eql?( anObject ) -> true or false ------------------------------------------------------------------------ Returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so: 1 == 1.0 #=> true 1.eql? 1.0 #=> false ~/prog/ruby$ ri Object#hash This is a test 'ri'. Please report errors and omissions on http://www.rubygarden.org/ruby?RIOnePointEight ------------------------------------------------------------ Object#hash obj.hash -> aFixnum ------------------------------------------------------------------------ Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used. Jason Creighton