10.8. Sorting enumerables

If you have a class, and you want to be able to arrange multiple instances of it in order, you need to do the following:

1.  Define a comparison method for the class (<=>).

2.  Place the multiple instances in a container, probably an array.

3.  Sort the container.

The key point is that although the ability to sort is granted by Enumerable, your class doesn’t have to mix in Enumerable. Rather, you put your objects into a container object that does mix in Enumerable. That container object, as an enumerable, has two sorting methods, sort and sort_by, which you can use to sort the collection.

In the vast majority of cases, the container into which you place objects you want sorted will be an array. Sometimes it will ...

Get The Well-Grounded Rubyist, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.