sort method

The sort method takes an enumerable collection and returns a new collection, sorted. For numbers, this is pretty straightforward, and you don't even need to provide any arguments for simple applications. For other objects, however, it's usually necessary to specify a block that will be used to sort the items by whatever criteria you specify.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# numbers sorted:
@numbers.sort
    #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# numbers sorted by negative values:
@numbers.sort{|a,b| 0 - a <=> 0 - b}
    #=> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Pet Inventory

Sorting with sort instead of sort_by can be time consuming for complex comparisons. Take this example, where pets are sorted by the simple quantity:

# sorting pets by quantity:
@inventory.sort.map(&:name)
    #=> ["rock", "scorpion", "monkey", "cat", "dog", "fish", "beetle"]

# all the comparisons required to sort:
#    dog vs scorpion
#    scorpion vs rock
#    cat vs scorpion
#    monkey vs scorpion
#    beetle vs scorpion
#    fish vs scorpion
#    fish vs beetle
#    beetle vs dog
#    fish vs dog
#    cat vs fish
#    monkey vs fish
#    dog vs cat
#    cat vs monkey

# total comparisons: 13
# total time: 0.0001 seconds

Seven collection items required 13 comparisons as the sort method compared various items to each other. Luckily, in a simple comparison it's not very harmful. Now let's try a more complex comparison:

# sorting pets by time-consuming secret code:
@inventory.sort{ |pet_a, pet_b| pet_a.secret_code <=> pet_b.secret_code }.name
    #=> ["beetle", "dog", "scorpion", "monkey", "rock", "fish", "cat"]

# all the comparisons required to sort:
#    342116e7 vs 3acf0f48
#    3acf0f48 vs a4977713
#    bfb82661 vs 3acf0f48
#    4a8b41d6 vs 3acf0f48
#    1dd19813 vs 3acf0f48
#    b0d58a4b vs 3acf0f48
#    342116e7 vs 1dd19813
#    b0d58a4b vs 4a8b41d6
#    4a8b41d6 vs a4977713
#    b0d58a4b vs a4977713
#    bfb82661 vs a4977713
#    bfb82661 vs b0d58a4b

# total comparisons: 12
# total time: 5.9021 seconds

Any comparisons involving time-consuming operations will suffer, the more items are in the collection. Even for this small collection of only seven items, sort_by is over three times as fast.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>