(4 ratings)   
By: math.umd.edu
You are already familiar with a couple of Ruby classes (Integer and String). The class Array is used to represent a collection of items.
Added: 23 June 2008    Views: 103  
PathComputers    Programming    Ruby
Keywords: computers   programming   ruby   coder   code   language   arrays  
Do you like this tutorial? Now you can support our team to add more :     
 
 
 

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 the Author :
math.umd.edu
Arrays In RUBY
Articles and Tutorials Directory by www.learnfobia.com
 Rate this tutorial : Rate 1Rate 2Rate 3Rate 4Rate 5
  |    Add to Favorites
  |    Send to Friend
  |    Print
Comments