Learning Ruby

How to sort an array

Use the Array "sort" method.

fruit = ["oranges", "apples", "bananas"]

sorted = fruit.sort 
# => ["apples", "bananas", "oranges"]
fruit
# => ["oranges", "apples", "bananas"]
fruit.sort! fruit
# => ["apples", "bananas", "oranges"]
Arrays are sorted by comparing each element of the array using the <=> comparison operator. When comparing two arrays themselves "<=>" checks and compares each element of the arrays. So for example:
array1 = ["a",7]
array2 = ["a",6]
array1 <=> array2 
# => would return +1 meaning array1 is greater than array2
So if you sort this array:
fruit = [ ["avacados", 1], ["apples", 2], ["carrots", 3] ]
# => you'll get
fruit.sort
# => [ ["apples", 2], ["avacados", 1], ["carrots", 3] ]

 

 

January 05, 2010 at 9:33 am