On Wed, 10 Nov 2004 01:08:38 +0900, Kevin Böògens <kevin / boergens.de> 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]])<h.sort.index([person2,h[person2]]) > 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? Myself, I would add a method to Enumerable. This lets you separate a lot of the logic: module Enumerable def each_permutation history = [] each do |item1| history.each{|item2| yield [item1,item2]} history << item1 end end end Then: h = {"john" => 41, "mary" => 31, "fred" => 10} h.each_permutation do |(person1, age1), (person2, age2)| puts "#{person1} shakes hands with #{person2}." + "Together they are #{age1+age2} years old." end HTH, Mark > TIA, > Kevin > >