0

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
2
  • 1
    "Any tips?" is hardly a proper question. Please have a look at to ask a good question and take your time to format the code properly. You can see a preview of your post in the bottom of the editing page. Commented Mar 27, 2019 at 23:25
  • @dedObed, Thank you for your input. Both are edited. Commented Mar 27, 2019 at 23:30

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

@ray Your edit changes the code's intention. That is too much.
You can address block as sort_by(&:last) with to format short in length.
@ray, I've updated my answer and added the link to explain it.
0

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]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.