Ruby:Sorting an Array

From Progzoo
Jump to: navigation, search

Sort a list in place

The method sort! can be used:

Sort the list 2,7,5,4.


[Font] [Default] [Show] [Resize] [History] [Profile]

Create a new sorted list

The method sort can be used:

Return a new list of the values 2,7,5,4 without modifying the original list.


[Font] [Default] [Show] [Resize] [History] [Profile]

Sort a list using a custom key function

A key can be associated with each item in the list to specify how they are to be sorted. The list is sorted according to the order of the keys, not the original values. You provide a key function, which maps each element to its key.

For example, to sort a list by order of increasing string length:


[Font] [Default] [Show] [Resize] [History] [Profile]

Sort a list using an anonymous custom comparator

You can create your own comparator. This mens that you decide how the sort is to be done. (Note: this method is slower than using keys.) You must provide a block that returns a negative, zero or a positive integer depending on how the first argument (let's call o1) compares to the second argument (let's call o2).

return -1 (or any negative number) if o1 comes before o2
return  0 if o1 and o2 are the same
return  1 (or any positive number) if o1 comes after o2


[Font] [Default] [Show] [Resize] [History] [Profile]