views:

94

answers:

2

If I have an array of employees, how can I sorted based on employee last name?

+5  A: 

Should be something like:

employees sortBy: [:a :b | a lastName > b lastName]
Chuck
+2  A: 

If we make these assumptions:

  1. The Array instance is held in a variable named employees
  2. The Array holds a collection of instances that all respond to the message lastName by returning a String instance
  3. You want to sort the collection in ascending order

Then you can get the job done with the following code fragment:

 employees asSortedCollection: [ :a :b | a lastName < b lastName ]

This code sends the asSortedCollection: keyword message to the Array instance named employees. It passes in the Block instance, delimited by the square brackets, as the parameter to that keyword message. The Block passed in has two arguments that are named a and b and are marked by the preceding colon character all before the | character. The code within the Block after the | character will then be used to sort all the elements from the employees Array and add them to a new instance of the class SortedCollection.

Note, though, that this code ends up returning a new collection that holds the same items also held by employees, but now in the desired order. In fact, that new collection holds onto the sort criteria (the Block instance that was used as the parameter to the asSortedCollection: message) and as you add more instances to that collection in the future they will automatically be inserted in the correct sort order.

R Peirson