Arrays
Updated Aug 24, 2023 ·
Overview
Arrays are useful for storing multiple items in a specific order. You can use it to keep things organized and access them by their position.
- Arrays store items in sequence
- Arrays are objects and have methods you can use
Arrays are mutable, so you can add, remove, or change items later. Ruby preserves the order of items, and the length shows how many items are inside.
numbers = [] # empty array
p numbers
numbers = [4, 8, 15, 16, 23, 42]
p numbers
p numbers.length
Output:
[]
[]
[4, 8, 15, 16, 23, 42]
6
You can mix types, but usually arrays hold similar items.
For example, a shopping list:
shopping_list = ["teddy bear", "water gun", "board game"]
p shopping_list
Output:
["teddy bear", "water gun", "board game"]
Arrays can also hold booleans or duplicates:
attendees = [true, true, false, true, false]
p attendees
Output:
[true, true, false, true, false]