From: "Brian Schröder" Date: 2004-11-10T01:21:53+09:00 Subject: Re: Iterating trough hash Hello Kevin, as the hash key is unique it should suffice to do it like this. h = {"john" => 41, "mary" => 31, "fred" => 10} h.each do | person1, age1 | h.each do | person2, age2 | next if person1 <= person2 puts "#{person1} shakes hands with #{person2}. Together they are #{age1 + age2} years old" end end Note that you made an error with the string interpolation. I assume you are coming from php where you only need the $, here in ruby we need the braces. Regards, Brian On Wed, 10 Nov 2004 01:08:38 +0900 Kevin B�rgens wrote: > Hi! > > This is my first ruby day. I started reading the ruby book two hours ago and > want to do something useful now :-) > I have a hash and I want to iterate trough all pairs of values. An example: > > h = {"john" => 41, "mary" => 31, "fred" => 10} > #insert control structure here > age=(h[person1]+h[person2]).to_s > puts "#person1 shakes hands with #person2. Together they are #age > years old" > > > The output could for example be: > > john shakes hands with mary. Together they are 72 years old > john shakes hands with fred. Together they are 51 years old > mary shakes hands with fred. Together they are 41 years old > > > what I do at the moment: > > h = {"john" => 41, "mary" => 31, "fred" => 10} > h.each_key{|person1| > h.each_key{|person2| > if h.sort.index([person1,h[person1]]) age=(h[person1]+h[person2]).to_s > puts "#{person1} shakes hands with #{person2}. Together they are > #{age} years old" > end }} > > Is there a more elegant way to do this? > > TIA, > Kevin > -- Brian Schr�der http://www.brian-schroeder.de/