sort

For sorting an array, note that sort returns the results in a new array, and does not modify the original.

.sort()

This will sort the items in this array, in ascending order. If the values contained are numbers, then they are compared numerically, and otherwise converted to strings and compared alphabetically.

/**
 * Generates 10 random numbers,
 * sorts them, and then prints them to the console.
 */

ns = []

10.times() do
    ns.push( rand(10).round() )
end

console( ns )

If your doing anything more complex then just sorting numbers or strings, then you should use the block version of sort.

.sort() { |a, b| ... }

This version takes a block, and allows you to then decide how the values are ordered. Each time the block is run, it is passed two values from the array, and the block should return a number depicting how they are related.

If a should appear before b, then a negative value should be returned (such as -1), and if a should appear after b, then a positive value should be returned (such as 1).

If both a and b are considered equal, and there is no preference in ordering, then 0 should be returned.

/**
 * Generates 10 random numbers,
 * and sorts them in reverse order using the block
 */
 
ns = []
10.times() do
    ns.push( rand(10).round() )
end

reverseNs = ns.sort() { |a, b| return b-a }
console( reverseNs )
/**
 * Advanced Sorting Example
 * 
 * Makes a large collection of Circles,
 * and then sorts them by their y value.
 * 
 * Once we have two sets of circles,
 * one sorted and one random,
 * we draw them.
 */

// Make our initial Circles
circles = []
250.times() do
    x = rand( 80, getScreenWidth()/2-80 )
    y = rand( 60, getScreenHeight()-50 )
    
    circles.push( new Circle(x, y) )
end

// Sort our circles
sorted = circles.sort() do |a, b|
    return a.getY() - b.getY()
end

// Draw Circles, on every frame
onEachFrame() do
    fill( :green )
    
    // draw points
    circles.each() { |p| p.draw(0, 0) }
    sorted.each() { |p| p.draw(getScreenWidth()/2, 0) }
    
    // draw info text
    setColor( :black ) do
        fillText( "Unsorted", getScreenWidth()*0.25 + 1, 20 + 1, true )
        fillText( "Sorted Y", getScreenWidth()*0.75 + 1, 20 + 1, true )
    end
    setColor( :white ) do
        fillText( "Unsorted", getScreenWidth()*0.25, 20, true )
        fillText( "Sorted Y", getScreenWidth()*0.75, 20, true )
    end
end

class Circle
    getset( x, y )
    
    def new( x, y )
        @x = x
        @y = y
    end
    
    def draw(x, y)
        setColor( :blue ) do
            fillCircle( @x+x, @y+y, 40, 40, true )
        end 
        setColor( :white ) do
            drawCircle( @x+x, @y+y, 40, 40, true )
        end
    end
end