Recipe 4.5. Sorting an ArrayProblemYou want to sort an array of objects, possibly according to some custom notion of what "sorting" means. SolutionHomogeneous
To sort objects based on one of their data members, or by the results of a method call, use
To do a more general sort, create a code block that compares the relevant aspect of any two given objects. Pass this block into the sort method of the array you want to sort. This code sorts an array of numbers in ascending numeric order, except that the number 42 will always be at the end of the list:
DiscussionIf there is one "canonical" way to sort a particular class of object, then you can have that class implement the <=> comparison operator. This is how Ruby automatically knows how to sort numbers in ascending order and strings in ascending ASCII order: Numeric and String both implement the comparison operator. The sort_by method sorts an array using a Schwartzian transform (see Recipe 4.6 for an in-depth discussion). This is the most useful customized sort, because it's fast and easy to define. In this example, we use sort_by to sort on any one of an object's fields.
If you pass a block into sort, Ruby calls the block to make comparisons instead of using the comparison operator. This is the most general possible sort, and it's useful for cases where sort_by won't work. The comparison operator and a sort code block both take one argument: an object against which to compare self. A call to <=> (or a sort code block) should return1 if self is "less than" the given object (and should therefore show up before it in a sorted list). It should return 1 if self is "greater than" the given object (and should show up after it in a sorted list), and 0 if the objects are "equal" (and it doesn't matter which one shows up first). You can usually avoid remembering this by delegating the return value to some other object's <=> implementation. See Also
|
Saturday, November 7, 2009
Recipe 4.5. Sorting an Array
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment