Pardon the mess, Play My Code is in beta!


sign up - lost password


[ ]

New arrays are created using square brackets. An empty Array are square brackets that contain nothing.

myEmptyArray = []

Arrays can also contain values when they are created. These are separated by commas, and are stored against an index, which starts at 0.

// a collection of names
names = [ "Brian", "Jenkins", "Tim", "Leo" ]

// a random list of numbers
numbers = [ 9, 39, 28, 54, 9, 2, 5, 5 ]

new Array()

Alternatively, you can use 'new Array()' instead of the square brackets, and this will return an empty array.

myEmptyArray = []
anotherEmptyArray = new Array()

new Array( size ) { |i| ... }

A third way of building an array is to state the size, and attach a block. The block is run for each index from 0 up to the given 'size'. The index is passed into the block, and the value returned is then set into the array at that location.

// an array of numbers from 0 to 10
numbers = new Array( 10 ) { |i| return i }

doubles = new Array( 10 ) { |i| return i*2 }

// an array containing the images: 'ship_0.png', 'ship_1.png' and 'ship_2.png'
images = new Array( 3 ) do |i|
    return new Image( 'ship_' + i + '.png' )

2D Arrays

A 2d array is just an array holding multiple arrays, but building this manually can be tiresome. So the Array constructor allows a second parameter, which will automatically build an array of arrays for you.

new Array( width, height )

Builds a new array with 'width' number of elements. Each of these is another Array, each with the size of 'height'. These are filled with null.

grid = new Array( width, height )

new Array( width, height ) { |x, y| ... }

A block can also be attached to allow you to fill the array elements as it is created. The x and y location in the array for that element are passed in, and you return the element to be set there.

 * Creates a grid of colours,
 * and then uses this grid to paint the screen.

width  =  getScreenWidth() / 10
height = getScreenHeight() / 10
grid = new Array( width, height ) do |x, y|
    return (x*y) % 255

onEachFrame() do
    fill( :black )
    grid.each() do |x, row|
        row.each() do |y, col|
            setColor( col, col, col )
            fillRect( x*10, y*10, 10, 10 )