From: Ara.T.Howard@... Date: 2004-11-10T05:23:39+09:00 Subject: Re: Iterating trough hash On Wed, 10 Nov 2004, Mark Hubbart wrote: >> if h.sort.index([person1,h[person1]]) < h.sort.index([person2,h[person2]]) >> >> says: >> >> if the name of person1 is less than the name of person2 OR the names are the >> SAME but the age of person1 is less than the age of person2. > > Um, no, I think this says: > > if the index of the first element that matches [person1, age1] is > greater than the > index of the first element that matches [person2, age2]. consider the meaning of the h.sort and how ruby will do it by default. h.sort => array of key value pairs sorted first on name then on age h.sort.index => look for the natural ordering of an entry where the ordering has been defined by ruby's Array#sort method you are correct in what you said - but what does that __mean__? if you think of what would cause an index to be less than the index of another entry you'll see what i mean: a particular key/val pair will only have a lesser index in the array produced by h.sort if either the name in the entry sorts first or the names are the same and the age sorts first. as you pointed out the names cannot be the same since the data is stored in a hash - so why include age in the search for ordering index when it can never be a tie breaker? eg this code would have the same effect if h.keys.sort.index(person1) < h.keys.sort.index(person2) my concern was that the OP included the age in the ordering search thinking it had some effect - it doesn't. in fact dermining the name's (or name/age pair) index into an ordered list is exactly the same as simply comparing names isn't it: harp:~ > cat a.rb h = {"john" => 41, "mary" => 31, "fred" => 10} puts '---' h.each_key do |person1| h.each_key do |person2| if h.sort.index([person1,h[person1]]) ruby a.rb --- john shakes hands with mary. Together they are 72 years old fred shakes hands with john. Together they are 51 years old fred shakes hands with mary. Together they are 41 years old --- john shakes hands with mary. Together they are 72 years old fred shakes hands with john. Together they are 51 years old fred shakes hands with mary. Together they are 41 years old so - why do you think the OP included age in the search? what was the code trying to say? kind regards. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | When you do something, you should burn yourself completely, like a good | bonfire, leaving no trace of yourself. --Shunryu Suzuki ===============================================================================