I have a list of Fruit
structs called basket
. Each Fruit
struct has a name
(a string) and a calories
(an int
Let's assume that your basket is an Array or a subclass thereof.
Enumerable.sort_by
As Gareth pointed out, Enumerable (included by Array) has a sort_by method that runs through each list item once. This is faster to run and faster to write once you get the hang of it.
# -f.calories to sort descending
# name.downcase to do a case-insensitive sort
basket = basket.sort_by { |f| [-f.calories, f.name.downcase] }
Array.sort
Coming from a Perl background, my first impulse is to grab the spaceship operator <=>. Cheeky little devil. Array has the sort and sort! methods that make it very useful. This solution is slower, and because it's longer it is more likely to introduce bugs. The only reason to use it is if you're dealing with people unfamiliar with Ruby and unwilling to find the right way on StackOverflow.
baseket.sort! { |a,b|
if a.calories == b.calories
a.name.downcase <=> b.name.downcase
else
# Reverse the result to sort highest first.
-(a.calories <=> b.calories)
end
}