From: Rein Henrichs Date: 2010-06-11T15:15:07+09:00 Subject: Re: comparing objects On 2010-06-10 22:52:14 -0700, Robert Dober said: > On Thu, Jun 10, 2010 at 6:48 PM, Mark Abramov wrote: >> Robert Dober wrote: >>> On Thu, Jun 10, 2010 at 5:30 PM, Rein Henrichs wrote: >>> overwriting #hash and #eql? breaks �Hash! >> That's not true, I think. > Judge for yourself > > require "forwardable" > > def count klass > ObjectSpace.each_object( klass ).to_a.size > end > class N > extend Forwardable > attr_reader :n > def_delegators :n, :hash > def eql? otha > n == otha.n > end > private > def initialize n > @n = n > end > end # class N > > > h = { N.new( 42 ) => true } > h[ N.new( 42 ) ] = 42 > p h > GC.start > p count(N) > > Cheers > R. This breaks Hash? Quite the opposite! This is precisely what is meant by "defining the semantics" of a class for use by hashes and the very behavior you want when you define #eql? and #hash in the first place! You wouldn't say that defining #<=> breaks Array#sort, so why would you say that this "breaks Hash"? This doesn't break Hash. If anything, it fixes it when using N objects as keys! -- Rein Henrichs http://puppetlabs.com http://reinh.com