sort! is a Ruby Array method that sorts the receiver in place. Sorting numbers is direct; sorting custom objects requires a comparison rule. section 10.8
The sorting behavior follows two paths:
- Use each element’s <=> method when the objects define a natural ordering. section 10.8
- Provide a block with two elements when the current operation needs another ordering or the elements lack <=>. section 10.8.1
- Normalize unlike values inside the block when their default comparison is incompatible, such as converting strings and integers with to_i. section 10.8.1
Sorting objects by a chosen attribute
A Painting class can compare prices through <=>, while a block can override that ordering for a particular operation, such as sorting by year. The same comparison pattern applies when using sort! on an Array. section 10.8 section 10.8.1
Listing 10.3 Painting class implementing the spaceship operator
class Painting
attr_reader :price
def initialize(price)
@price = price
end
def to_s
"My price is #{price}." 1
end
def <=>(other_painting)
self.price <=> other_painting.price 2
end
end
This implementation shows how an object supplies the <=> comparison that an Array sorting operation can use. section 10.8
