Product Site

5.3.19.1. Sorting non-strings

Sorting is not limited to string values. Any object that inherits the Comparable MIXIN class and implements a compareTo method can be sorted. The DateTime class and TimeSpan class are examples of built-in Rexx classes that can be sorted. Any user-created class may also implement a compareTo method to enable sorting. For example, consider the following simple class:
Example 5.210. Non-string sorting
::class Employee inherit Comparable

::attribute id
::attribute name

::method init
  expose id name
  use arg id, name

::method compareTo
  expose id
  use arg other
  return id~compareTo(other~id) -- comparison performed using employee id

::method string
  expose name
  return "Employee" name

The Employee class implements its sort order using the employee identification number. When the sort method needs to compare two Employee instances, it will call the compareTo method on one of the instances, passing the second instance as an argument. The compareTo method tells the sort method which of the two instances should be first.
Example 5.211. Comparison during sorting
    a = .array~new
    a[1] = .Employee~new(654321, "Fred")
    a[2] = .Employee~new(123456, "George")
    a[3] = .Employee~new(333333, "William")

    a~sort

    do employee over a
       say employee    -- sorted order is "George", "William", "Fred"
    end