programming.nbk: Home | Index | Next Page: Ruby: Blocks | Previous Page: Ruby


 Ruby: Arrays

An array holds a collection of object references. Each position of the array is identified by a non-negative integer.

Creating an array with an array literal:

    a = [3.1, "pie", 99]

Creating an array explicitly with a array object:

    b = array.new

Arrays are indexed with the [] operator.

Array indexes less than zero are from the right end:

    a = [ 1, 3, 5, 7, 9 ]  
    a[-1]  » 9  
    a[-2]  » 7  
    a[-99]  » nil  

You can index an array with a pair of numbers. This returns a new array that is a subset of the original:

    a = [ 1, 3, 5, 7, 9 ]  
    a[1..3]  » [3, 5, 7]  

Array elements can be assigned to with the []= operator. Any gap formed is filled with nil. Array elements can be references to arrays.

    a = [ 1, 3, 5, 7, 9 ] » [1, 3, 5, 7, 9] 
    a[1] = 'bat' » [1, "bat", 5, 7, 9] 
    a[-3] = 'cat' » [1, "bat", "cat", 7, 9] 
    a[3] = [ 9, 8 ] » [1, "bat", "cat", [9, 8], 9] 
    a[6] = 99 » [1, "bat", "cat", [9, 8], 9, nil, 99] 

If the index in the []= operator is a range, the elements of the range in the original array are replaced with the contents of the right side. If the length of the range is zero, the right side contents are placed before the referenced element.

    a = [ 1, 3, 5, 7, 9 ] » [1, 3, 5, 7, 9] 
    a[2, 2] = 'cat' » [1, 3, "cat", 9] 
    a[2, 0] = 'dog' » [1, 3, "dog", "cat", 9] 
    a[1, 1] = [ 9, 8, 7 ] » [1, 9, 8, 7, "dog", "cat", 9] 
    a[0..3] = [] » ["dog", "cat", 9] 
    a[5] = 99 » ["dog", "cat", 9, nil, nil, 99] 

See Ruby in a Nutshell, p 59 to 64


programming.nbk: Home | Index | Next Page: Ruby: Blocks | Previous Page: Ruby


Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time