From: Farrel Lifson Date: 2006-09-14T00:51:43+09:00 Subject: Re: What does it take to make an object hashable, no really... On 13/09/06, Tim Pease wrote: > On 9/13/06, Just Another Victim of the Ambient Morality > wrote: > > Suppose I want to define a class and be able to use this class as a key > > to a hash. How does one do this? ...And please test your response before > > posting it. > > Chapter 22 of the Programming Ruby, The Pragmatic Programmer's Guide > > A key must respond to "hash" and the value returned must not change. > > What is not in the book is that you must also provide an eql? method > that evaluates to true when two objects are equivalent. > > class C > def hash() "C".hash end > end > > h = {} > h[C.new] = 1 > h[C.new] > > => nil > > class C > def eql?(other) true end > end > > h[C.new] > > => 1 > > > > > Secondly, if an objects works in a hash, is it guaranteed to work in a > > set? > > No idea about this one. Have not used the Ruby Set class thus far. > > TwP > > Is there a reason why an implementation of eql? is needed instead of just being able to define <=>? Farrel