Product Site

5.3.19. Sorting Ordered Collections

Any ordered collection, such as non-sparse Arrays or Lists can have its elements placed into sorted order using the sort method. The simplest sort is sorting an array of strings.
Example 5.209. Array class — sorting
myArray = .array~of("Zoe", "Fred", "Xavier", "Andy")
myArray~sort

do name over myArray
   say name
end

will display the names in the order "Andy", "Fred", "Xavier", "Zoe".

The sort method orders the strings by using the compareTo method of the String class. The compareTo method knows how to compare one string to another, and returns the values -1 (less than), 0 (equal), or 1 (greater than) to indicate the relative ordering of the two strings.