|
Arrays are used to store collections of data objects.If this sounds too fancy for you, try imagining a situation like this:
You want to order pizza online from your local pizzeria which just happens to also offer an online ordering application.
They offer standard pizzas but they also allow customers to order their custom made pizza by offering them the possibility of choosing the type of dough used and the toppings.
How do you think the application "remembers" which toppings are available to customers? They're probably using an array, that's the answer.
Something like this:
toppings = [onions,mushrooms,pineapple,anchovies,salami,gorgonzola]
Let's dissect this example now and learn how arrays are used at the same time:
Each object in the array above has an unique key assigned to it.This is very useful when you want to address only one of the elements included in the array.The first element of the array is at position 0, so this means that toppings[0] will return "onions"; toppings[1] will return "mushrooms" and so on.
If you ever need just to create an empty array and add data to it later, you use the "new" method:
toppings = Array.new
If later one you want to assign elements to the array, you would do it like this:
toppings[0] = "onions"
toppings[1] = "mushrooms"
What if you wanted to create an array from a list of give strings? You can do it very easily like this:
toppings = %w[onions mushrooms pineapple anchovies salami gorgonzola]
Once that done, you simply reference an element by using it's index key:
toppings[4]
Here's a list of methods that you can use with arrays to test for different situations:
Test if the array is empty:
toppings.empty?
See how many elements the array contains:
toppings.size
or
puts toppings.length
Delete an element from an array:
toppings.delete "salami"
|