Sort a collection of objects by number (highest first) then by letter (alphabetical)

别等时光非礼了梦想. 提交于 2019-11-28 08:48:38
countries.sort_by do |country|
  medals = country.gold + country.silver + country.bronze
  [-medals, -country.gold, -country.silver, country.name]
end

A simple method is to use sort_by with some arbitrary formatted string, like:

countries.sort_by do |c|
  "%010d-%010d-%010d-%s" % [ c.gold, c.silver, c.bronze, c.name ]
end

This converts all the countries in to an ASCII sortable listing by padding the number of medals won to the presumably outrageous 10 places. If anyone wins more than ten billion medals your program may malfunction, but that seems like a reasonable constraint.

In Java you would implement comparable on your object and then it could easily be sorted in an ArrayList or Array. Is there a mechanism in Ruby to tell how to compare two of your "Country" objects?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!