About this chapter |
|
What can arrays do? |
You are already familiar with a couple of Ruby classes (Integer and String). The class Array is used to represent a collection of items.
This is best seen through an example:
$ irb --simple-prompt >> numbers = [ "zero", "one", "two", "three", "four" ] => ["zero", "one", "two", "three", "four"] >> numbers.class => Array |
Here the class method tells us that the variable numbers is an Array. You can access the individual elements of the array like this:
>> numbers[0] => "zero" >> numbers[1] => "one" >> numbers[4] => "four" |
You can add more entries to the array by simply typing:
>> numbers[5] = "five" => "five" |
Notice that the entries in the array are stored sequentially, starting at 0. An array can contain any number of objects. The objects contained in the array can be manipulated just as before.
>> numbers[3].class => String >> numbers[3].upcase => "THREE" >> numbers[3].reverse => "eerht" |
Warning: Notice that Array's start counting at 0, not 1 |
What kind of things can you put on arrays? Well, any object really. How about strings and integers?:
>> address = [ 284, "Silver Spring Rd" ] => [284, "Silver Spring Rd"] |
How about another array?
>> addresses = [ [ 284, "Silver Sprint Rd" ], [ 344, "Ontario Dr" ] ] => [[284, "Silver Sprint Rd"], [344, "Ontario Dr"]] >> addresses[0] => [284, "Silver Sprint Rd"] >> addresses[1] => [344, "Ontario Dr"] >> addresses[0][0] => 284 >> addresses[0][1] => "Silver Sprint Rd" |
Can you see why arrays are so cool?
About this chapter |
|
What can arrays do? |