Consider a class Team, with class variables ‘wins’ and ‘losses’. I wish to sort an array of Teams by the win:loss ratio, such that:
5:0 > 3:0 > 1:0 > 3:1 > 5:5 > 3:3 > 1:3 > 0:1 > 0:3 > 0:5
I already have a (partial) hacked together solution that I’m not happy with, and I’m wondering if there is a cleaner/more elegant/simpler way to solve this problem.
def ratio
if @losses == 0 then
return 1000000+@wins
end
if @wins == 0 then
return 0-@losses
end
return @wins/@losses
end
(This does not fix 5:5 > 3:3)
Which would be in the Team class and could be used like this:
teams.sort! { |a, b| b.ratio <=> a.ratio }
What is the simplest way to solve this? (Solutions does not have to be Ruby, I’m happy with anything that is OO)
I don’t speak Ruby, but a Python approach which would give your desired results would use a tuple for a key (in the decorate-sort-undecorate “Schwartzian transform” idiom.)
For example, you could rank by win fraction, then number of wins, then (negative) number of losses, which would give your desired ordering:
I don’t know what the Ruby equivalent is, unfortunately, but I gather that there’s a
sort_bymethod floating around somewhere.