I have a list of Fruit structs called basket. Each Fruit struct has a name (a string) and a calories (an int
If you need to sort Fruits a lot, you should probably do a little more work up front and make your objects comparable.
For this, you need to implment the Spaceship-Operator (<=>) and include Comparable.
class Fruit
attr_accessor :name, :color
def <=>(other)
# use Array#<=> to compare the attributes
[self.name.downcase, self.color] <=> [other.name.downcase, other.color]
end
include Comparable
end
then you can simply do:
list_of_fruits.sort
Comparable also gives you many other methods (==, <, >) for free, so you can do things like if (apple < banana) (see the documentation for the Comparable Module for more info)
<=>, is specified to return -1 if self is smaller than other, +1 if other is smaller and 0 if both objects are equal.