<- Arrays
Iterators ->

What can arrays do?

This is all very nice, but can I do anything cool with arrays? You sure can.

Array#sort

You can sort arrays with the method Array#sort.


>> primes = [ 11, 5, 7, 2, 13, 3 ]
=> [11, 5, 7, 2, 13, 3]
>> primes.sort 
=> [2, 3, 5, 7, 11, 13]
>> 
?> names = [ "Melissa", "Daniel", "Samantha", "Jeffrey"]  
=> ["Melissa", "Daniel", "Samantha", "Jeffrey"]
>> names.sort
=> ["Daniel", "Jeffrey", "Melissa", "Samantha"]
                       

Array#reverse

You can reverse arrays:


>> names
=> ["Melissa", "Daniel", "Samantha", "Jeffrey"]
>> names.reverse 
=> ["Jeffrey", "Samantha", "Daniel", "Melissa"]
                       

Array#length

You can find out how long the array is:


>> names.length 
=> 4
                       

Array arithmetic

The methods Array#+, Array#-, and Array#* work the way that you would expect. There is no Array#/ (how would you divide an array?)


>> names = [ "Melissa", "Daniel", "Jeff" ]
=> ["Melissa", "Daniel", "Jeff"]
>> names + [ "Joel" ] 
=> ["Melissa", "Daniel", "Jeff", "Joel"]
>> names - [ "Daniel" ]
=> ["Melissa", "Jeff"]
>> names * 2
=> ["Melissa", "Daniel", "Jeff", "Melissa", "Daniel", "Jeff"]
                       

Naturally, their friends +=, -= and *= are still with us.

Printing arrays

Finally, you can print arrays.


>> names
=> ["Melissa", "Daniel", "Jeff"]
>> puts names 
Melissa
Daniel
Jeff
=> nil
                       

Remember that the nill means that puts returns nothing. What do you think happens if you try to convert an array to a string with Array#to_s?


>> names
=> ["Melissa", "Daniel", "Jeff"]  
>> names.to_s
=> "MelissaDanielJeff"
>> primes
=> [11, 5, 7, 2, 13, 3]
>> primes.to_s
=> "11572133"
                       

Exercises

  1. What do you think that this will do?:

    
    >> addresses = [ [ 285, "Ontario Dr"], [ 17, "Quebec St"], [ 39, "Main St" ] ]
    >> addresses.sort
                           

    How about this?:

    
    >> addresses = [ [ 20, "Ontario Dr"], [ 20, "Main St"] ]
    >> addresses.sort
                           

    Try these out in irb

<- Arrays
Iterators ->