K
Kevin Börgens
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?
TIA,
Kevin
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?
TIA,
Kevin