From: "David G. Andersen" Date: 2004-11-10T01:26:03+09:00 Subject: Re: Iterating trough hash On Wed, Nov 10, 2004 at 01:17:27AM +0900, James Edward Gray II scribed: > > 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. Canonicalizing the order and making sure that john doesn't shake hands with himself, as he would in the above revision. This is one case where the "for loop" solution is probably more elegant: h = {"john" => 41, "mary" => 31, "fred" => 10} people = h.keys (0..people.length).each do |p1| (p1+1...people.length).each do |p2| puts "..." end end (note the '...' in the second for loop) -dave -- work: dga@lcs.mit.edu me: dga@pobox.com MIT Laboratory for Computer Science http://www.angio.net/