Hi all,
I didn't want my first bit of participation on this list to be
something this silly. But I'm afraid I missed something vital in my 48
hour crash course.
If someone could take 10 seconds and tell me what I'm doing wrong I'd
greatly appreciate it and will give you props in my epitaph.
Feel free to point out and make fun of the style too I have thick skin.
I want to use an object as a key in a Hash.
here's some example code...
def main
聽聽puts "running this script..."
聽聽testpointid
end
def testpointid
聽聽p = PointID.new(1,1)
聽聽p2 = PointID.new(1,2)
聽聽pdup = PointID.new(1,1)
聽聽print "p!=pdup\n" if p!=pdup
聽聽d = Hash.new()
聽聽d[p]="point1"
聽聽d[p2]="point2"
聽聽#both of these return nil and I don't understand why
聽聽print "PointID test failed" if d[p]!="point1"
聽聽print "PointID test failed" if d[pdup]!="point1"
聽聽#this works, but it's not quite the interface I want
聽聽d[p.hash]="point1"
聽聽d[p2.hash]="point2"
聽聽print "PointID test failed" if d[p.hash]!="point1"
聽聽print "PointID test failed" if d[pdup.hash]!="point1"
end
class PointID
聽聽attr_reader :x,:y
聽聽def initialize(x,y)
聽聽聽聽@x = x
聽聽聽聽@y = y
聽聽聽聽@x.freeze
聽聽聽聽@y.freeze
聽聽end
聽聽def hash
聽聽聽聽return [@x.object_id,@y.object_id].to_s
聽聽end
聽聽def ==(other)
聽聽聽聽return hash == other.hash
聽聽end
聽聽def to_s
聽聽聽聽return hash()
聽聽end
end
路路路
--
Thomas G. Willis
http://paperbackmusic.net