C_B
C_B

Reputation: 7

How to sort an array of arrays in ascending order

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

Answers (2)

mechnicov
mechnicov

Reputation: 15248

Just use Array#sort with block

golf.sort { |a, b| a.last <=> b.last }

or Enumerable#sort_by

golf.sort_by { |a| a.last }

The second variant can be shortened using Proc

golf.sort_by(&:last)

Upvotes: 4

Srinidhi Gs
Srinidhi Gs

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

Related Questions