From: ranx2@... (Ranx) Date: 2001-07-21T10:07:32+09:00 Subject: [ruby-talk:18221] Re: how does hash locate pairs? Hi Steve, You need to have a method (say to_s) in your Class that returns a string (unique for each min, max pair) def to_s "#{@min}-#{@max}" end You could then use h[Bin_key.new(1,10).to_s]="Hello World" and later access it as h["1-10"] (or even h[Bin_key.new(1,10).to_s]) I dont think hash can be indexed by objects. Only by strings. Ranx stephen.hill@motorola.com (Steve Hill) wrote in message news:... > Hi, > in methods such as [], []=, fetch, etc. how does Hash locate a key, > value pair. > > For example, in > > h=Hash.new > h[0]="foo" > h[1]="bar" > > puts h[0] > > how does the Hash object h locate the appropriate pair. > > I ask this because I am having problems in getting a hash to work when > the keys are objects that I have created - in this case a Bin_key > object that holds the endpoints of a bin. I've tried defining a == and > a <=> method and I'm not getting anywhere. Here is my bin_key object > > (sob story: I'm posting on NT while working on an x-term under exceed > nt and the copy and paste doesn't work, so this is a retype - please > excuse typos!) > > class Bin_key > def initialize(min,max) > @max=max > @min=min > end > > def ==(x) > x>@min && x<=@max > end > > def <=> > if x<@min then return 1 > elsif x>@min && x<=@max then return 0 > return 1 > end > end > end > > now if I define some code to use Bin_key > > h=Hash.new > h[Bin_key.new(1,10)]="Hello World" > > h[5] ->nil! > > This is odd since if I write > > h.each {|k,v| puts v if k==5} -> "Hello World" > > Can anyone explain what is going on please? > > Best regards > > Steve