Arrays help you keep many items together in one place. They make it easy to store, find, and use groups of things in Ruby.
0
0
Why arrays are fundamental in Ruby
Introduction
When you want to keep a list of your favorite movies.
When you need to store scores of players in a game.
When you want to remember shopping items to buy.
When you want to loop through a set of names to greet each person.
When you want to sort or search through a collection of data.
Syntax
Ruby
class Array # You create an array with square brackets [] # Example: my_array = [1, 2, 3] # You can add items with push or << # Example: my_array.push(4) # Or: my_array << 5 # You get items by index starting at 0 # Example: my_array[0] # returns first item end
Arrays in Ruby can hold any type of item: numbers, words, or even other arrays.
Indexes start at 0, so the first item is at position 0.
Examples
This creates an empty array with no items.
Ruby
empty_array = []
puts empty_array.inspectAn array with one item. Accessing index 0 gives that item.
Ruby
single_item_array = [42] puts single_item_array[0]
Access the last item 'cherry' using index 2.
Ruby
fruits = ["apple", "banana", "cherry"] puts fruits[2]
Add items to an empty array using << and push methods.
Ruby
numbers = [] numbers << 10 numbers.push(20) puts numbers.inspect
Sample Program
This program shows how to create an array, add items, access an item by index, and loop through all items.
Ruby
puts "Create an empty array for colors:" colors = [] puts colors.inspect puts "Add colors to the array:" colors << "red" colors.push("green") colors << "blue" puts colors.inspect puts "Access the first color:" puts colors[0] puts "Loop through all colors:" colors.each do |color| puts "Color: #{color}" end
OutputSuccess
Important Notes
Arrays are fast to access by index (O(1) time).
Adding items at the end is usually fast (amortized O(1)).
Common mistake: forgetting that indexes start at 0, so the first item is at index 0, not 1.
Use arrays when you need ordered collections and quick access by position.
Summary
Arrays store many items together in order.
You can add, access, and loop through items easily.
They are a basic and powerful tool in Ruby programming.