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
=> #<HashableClass:0x2dc4270>
irb(main):004:0> h2 = HashableClass.new
=> #<HashableClass:0x2dc1c78>
irb(main):005:0> h1.hash
=> 23994680
irb(main):006:0> h2.hash
=> 23989820
irb(main):007:0> hash = {h1=>"H1",h2=>"H2"}
=> {#<HashableClass:0x2dc4270>=>"H1", #<HashableClass:0x2dc1c78>=>"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