数组中的信息:
scores = %w[ScoreA ScoreB ScoreC ScoreD ScoreE ScoreF ScoreG ScoreH ScoreI ScoreJ]
需要按照高尔夫球得分的升序显示。
任何人都可以帮助按升序对输出进行排序吗?
golf = scores.map do |score_number|
print "Enter the score for #{score_number}:"
[score_number, gets.to_i]
end
puts golf.sort
答案 0 :(得分:4)
只需在块中使用Array#sort
golf.sort { |a, b| a.last <=> b.last }
golf.sort_by { |a| a.last }
使用Proc
的第二个变体can be shortened
golf.sort_by(&:last)
答案 1 :(得分:0)
只需在块中使用Array#sort
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]]