From: Mark Hubbart Date: 2004-11-10T03:28:33+09:00 Subject: Re: Iterating trough hash On Wed, 10 Nov 2004 02:03:45 +0900, ara.t.howard@noaa.gov wrote: > > > On Tue, 9 Nov 2004, Kevin [ISO-8859-15] B�rgens wrote: > > > Hi! > >> #!/usr/bin/env ruby > >> > >> h = {"john" => 41, "mary" => 31, "fred" => 10} > >> h.each_key do |person1| > >> h.each_key do |person2| > >> puts "#{person1} shakes hands with #{person2}. " + > >> "Together they are #{h[person1] + h[person2]} years old." > >> end > >> end > > No, this programm would iterate like this > > john john > > john mary > > john fred > > mary john > > mary mary > > mary fred > > fred john > > fred mary > > fred fred > > > >> I'm not very clear on what you were aiming for with the if statement, > >> but if you tell me, I can probably add that back a little slimmer too. > > Therefore I used the example with shaking hands. You don't shake hands with > > yourself and it doesn't matter who is person1 or person2 > > > > TIA, > > Kevin > > that makes sense - but why, in your code, are you checking that the person's > name AND/OR age are less than the other person? eg this line > > 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]. > > example: > > harp:~ > irb > > irb(main):001:0> list = ['john', 42], ['john', 41] > => [["john", 42], ["john", 41]] > > irb(main):002:0> a, b = list.first, list.last > => [["john", 42], ["john", 41]] > > irb(main):003:0> list.index(a) > => 0 > > irb(main):004:0> list.index(b) > => 1 > > irb(main):005:0> list.index(a) < list.index(b) > => true > > and john is shaking hands with john. ruby sorts array by using this algorithim: > > compare the first elements, if tied > compare the second elements, if tied > compare the third elelments, etc.... > etc.... > > so the comparison you are making by checking the sort order (index position of > entry) checks both name AND age - which may or may not be what you want. But, since this array starts out its life as a hash, there will never be duplicate names. So the ages will never be compared. cheers, Mark > > cheers and welcome to ruby! > > > > -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 > =============================================================================== > >