From: Farrel Lifson Date: 2006-09-14T00:11:28+09:00 Subject: Re: What does it take to make an object hashable, no really... On 13/09/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. > Secondly, if an objects works in a hash, is it guaranteed to work in a > set? > Thank you... > > > > > As far as I know all objects respond to .hash and can therefore be used as keys. irb(main):001:0> class HashableClass irb(main):002:1> end => nil irb(main):003:0> h1 = HashableClass.new => # irb(main):004:0> h2 = HashableClass.new => # irb(main):005:0> h1.hash => 23994680 irb(main):006:0> h2.hash => 23989820 irb(main):007:0> hash = {h1=>"H1",h2=>"H2"} => {#=>"H1", #=>"H2"} irb(main):008:0> hash[h1] => "H1" If you undefine hash or have it return nil, then you can run into problems: irb(main):009:0> def h1.hash irb(main):010:1> nil irb(main):011:1> end => nil irb(main):012:0> hash[h1] NoMethodError: undefined method `%' for nil:NilClass from (irb):12:in `[]' from (irb):12 irb(main):013:0> Farrel