From: "Brian Schröder" Date: 2004-11-10T01:24:20+09:00 Subject: Re: Iterating trough hash On Wed, 10 Nov 2004 01:17:27 +0900 James Edward Gray II wrote: > On Nov 9, 2004, at 10:08 AM, Kevin B�rgens wrote: > > > 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? > > Well, we can simplify that a bit. How about: > > #!/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 > > __END__ > > 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. > > Hope that helps. > > James Edward Gray II > > I think he did not want ordered pairs, and only pairs with unequal members. On a site note, I think there should be a performance penalty, in looking up the values in the hash after getting the key. I'd imagine that .each do | person, age | would be faster. Regards, Brian -- Brian Schr�der http://www.brian-schroeder.de/