Ruby Monstas


Arrays

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

Examples

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

Syntax

Syntax:
[item1, item2, ...]

Empty array:
[]

Length

Try this in IRB!

my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits.length
=> 3
[].length
=> 0

Accessing items

Try this in IRB!

my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits[1]
=> "Apple"
Syntax:
array[index]
Note: Each element in the array has a so-called index an integer denoting the position of the element in the array

Note: Indices always start at 0, so the element with index 1 is the second element

Accessing items

Try this in IRB!

my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits[3]
=> nil
Note: If we try to access items beyond the length of the array, we get
nil

Accessing items

Try this in IRB!

my_favourite_fruits = ["Banana", "Apple", "Water melon"]
my_favourite_fruits.first
=> "Banana"
my_favourite_fruits.last
=> "Water melon"
Note:
.first
and
.last
are more convenient than
[0]
and
[2]

Appending

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

Changing items

Try this in IRB!

my_favourite_fruits[2] = "Mango"
my_favourite_fruits
=> ["Banana", "Apple", "Mango", "Orange"]
Syntax:
array[index] = new_item

Deleting items

Try this in IRB!

my_favourite_fruits.delete("Mango")
my_favourite_fruits
=> ["Banana", "Apple", "Orange"]

Deleting items

Try this in IRB!

my_favourite_fruits.delete_at(2)
my_favourite_fruits
=> ["Banana", "Apple"]

Additional Resources

Ruby For Beginners: Arrays

Ruby-doc: Array

What questions do you have?