Arrays
Arrays are lists of things
They are the most important "collection type" in Ruby
They allow you to store many things in one variable
my_favourite_fruits = ["Banana", "Apple", "Water melon"]
monthly_expenses = [342.75, 108.20, 241.00, 632.15, 499.55]
fibonacci_numbers = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Note: Each element in the array has the same type
Note: Elements are in a defined order
Note: Arrays can have 0 up to however many entries you want
[item1, item2, ...]
[]
Try this in IRB!
my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits.length
=> 3
[].length
=> 0
Try this in IRB!
my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits[1]
=> "Apple"
array[index]
Note: Indices always start at 0, so the element with index 1 is the second element
Try this in IRB!
my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits[3]
=> nil
nil
Try this in IRB!
my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits.first
=> "Banana"
my_favourite_fruits.last
=> "Water melon"
.firstand
.lastare more convenient than
[0]and
[2]
Try this in IRB!
my_favourite_fruits << "Orange"
=> ["Banana", "Apple", "Water melon", "Orange"]
Note: We can use the "shovel operator" to add elements to the end of an array
Try this in IRB!
my_favourite_fruits[2] = "Mango"
my_favourite_fruits
=> ["Banana", "Apple", "Mango", "Orange"]
array[index] = new_item
Try this in IRB!
my_favourite_fruits.delete("Mango")
my_favourite_fruits
=> ["Banana", "Apple", "Orange"]
Try this in IRB!
my_favourite_fruits.delete_at(2)
my_favourite_fruits
=> ["Banana", "Apple"]
What questions do you have?