Reputation: 7
Information in an array:
scores = %w[ScoreA ScoreB ScoreC ScoreD ScoreE ScoreF ScoreG ScoreH ScoreI ScoreJ]
needs to be presented in ascending order of the golf scores.
Can anyone help sorting the output in ascending order?
golf = scores.map do |score_number|
print "Enter the score for #{score_number}:"
[score_number, gets.to_i]
end
puts golf.sort
Upvotes: 0
Views: 125
Reputation: 15248
Just use Array#sort
with block
golf.sort { |a, b| a.last <=> b.last }
golf.sort_by { |a| a.last }
The second variant can be shortened using Proc
golf.sort_by(&:last)
Upvotes: 4
Reputation: 85
Just use Array#sort
with block
golf.sort { |x, y| x[1] <=> y[1] }
=> [["ScoreH", 1], ["ScoreB", 3], ["ScoreD", 4], ["ScoreF", 9], ["ScoreA", 10], ["ScoreJ", 23], ["ScoreG", 45], ["ScoreC", 67], ["ScoreI", 87], ["ScoreE", 88]]
Upvotes: 0