Arrays
Reviewed & published by Brayan K
Ruby is a dynamic, beginner-friendly programming language, and an Array is its workhorse collection — an ordered, index-addressable list that holds any kind of value.
Part of the free Ruby course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
By the end of this lesson you'll create arrays, read items by index, add and remove elements, and use Ruby's rich array methods.
What You'll Learn in This Lesson
- Creating arrays and reading items by index
- Negative indexes, first, last, and length
- Adding and removing with push, <<, and pop
- Slicing with ranges like arr[1..3]
- Transforming with sort, reverse, uniq, and sum
- Converting between arrays and strings (join/split)
1️⃣ Creating, Indexing, and Modifying
Write an array with square brackets and commas. Read any item by its zero-based index, or use negative indexes to count from the end. Add with push / << and remove the last with pop.
# An Array is an ordered list of values. Indexes start at 0.
fruits = ["apple", "banana", "cherry"]
puts fruits[0] # -> apple (first item)
puts fruits[1] # -> banana
puts fruits[-1] # -> cherry (negative counts from the end)
puts fruits.length # -> 3
puts fruits.first # -> apple
puts fruits.last # -> cherry
# Add and remove items:
fruits.push("date") # add to the end (same as fruits << "date")
fruits << "elderberry"
puts fruits.inspect # -> ["apple", "banana", "cherry", "date", "elderberry"]
removed = fruits.pop # remove and return the last
puts removed # -> elderberry
puts fruits.include?("banana") # -> true2️⃣ Slicing and Transforming
Grab a chunk with a range like arr[1..3]. Then transform with methods that return new arrays: sort, reverse, uniq, plus aggregates like min, max, and sum. Use join/split to move between arrays and strings.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Slicing: grab a range of items
puts numbers[1..3].inspect # -> [1, 4, 1] (indexes 1 to 3)
# Common array methods:
puts numbers.sort.inspect # -> [1, 1, 2, 3, 4, 5, 6, 9]
puts numbers.reverse.inspect # -> [6, 2, 9, 5, 1, 4, 1, 3]
puts numbers.uniq.inspect # -> [3, 1, 4, 5, 9, 2, 6] (dups removed)
puts numbers.min # -> 1
puts numbers.max # -> 9
puts numbers.sum # -> 31
# Join into a string, and split back:
words = ["learn", "ruby", "fast"]
puts words.join(" ") # -> learn ruby fast
puts "a,b,c".split(",").inspect # -> ["a", "b", "c"]Your turn. Summarise a list of test scores. Fill in the two TODO method calls, then run it.
# 🎯 YOUR TURN — replace each TODO, then run with: ruby scores.rb
# Start with a list of test scores
scores = [88, 72, 95, 61, 88] # 👉 change these numbers if you like
# 1) Print how many scores there are
puts "Count: #{scores.length}"
# 2) Print the highest and lowest score
puts "High: #{scores.max}" # 👉 TODO: use the right method
puts "Low: #{scores.min}" # 👉 TODO: use the right method
# 3) Print the average (sum / count — use to_f to keep decimals!)
average = scores.sum.to_f / scores.length
puts "Average: #{average.round(1)}"
# 4) Print the sorted scores, highest first
puts "Sorted: #{scores.sort.reverse.inspect}"
# ✅ Expected output:
# Count: 5
# High: 95
# Low: 61
# Average: 80.8
# Sorted: [95, 88, 88, 72, 61]Mini-Challenge: A Unique Guest List
Clean up a guest list by removing duplicates, alphabetising, and joining. Run with ruby guests.rb.
# 🎯 MINI-CHALLENGE: a unique guest list.
# Save as guests.rb and run with: ruby guests.rb
#
# 1. Start with an array of names that has some duplicates.
# 2. Use .uniq to remove duplicates.
# 3. Use .sort to alphabetise them.
# 4. Print the count and the cleaned list joined by ", ".
#
# ✅ Example output (from ["Sam","Ada","Sam","Bo"]):
# 3 guests: Ada, Bo, Sam
# your code hereCommon Errors (and the fix)
- Off-by-one indexing — The first item is arr[0], and the last is arr[arr.length - 1] or simply arr[-1].
- Reading past the end returns nil — arr[99] on a short array is nil, not an error. Check length first.
- sort vs sort! — sort returns a new array; sort! mutates in place. Pick deliberately.
- puts vs puts inspect — puts arr prints items line by line; use arr.inspect (or p arr) to see the structure.
- Comparing mixed types in sort — Sorting [1, "a"] raises an error; keep elements comparable.
Pro Tips
- 💡 %w shortcut: %w[a b c] makes ["a", "b", "c"] without quotes and commas.
- 💡 p for quick debugging: p arr prints arr.inspect in one keystroke.
- 💡 Array math: [1,2,3] - [2] gives [1,3]; a & b is the intersection.
📋 Quick Reference — Arrays
| Concept | Ruby Syntax |
|---|---|
| Create | [1, 2, 3] |
| First / last / nth | arr.first / arr[-1] |
| Add / remove | arr << x / arr.pop |
| Slice | arr[1..3] |
| Sort / unique | arr.sort / arr.uniq |
| Join | arr.join(", ") |
🎉 Lesson Complete!
- ✅ Arrays are ordered lists, indexed from 0
- ✅ Negative indexes count from the end; first/last help too
- ✅ Add with <</push, remove with pop
- ✅ sort, uniq, sum, and ranges transform data
- ✅ inspect / p reveal an array's structure
Practice quiz
Given fruits = ["apple", "banana", "cherry"], what does fruits[-1] return?
- "apple"
- "cherry"
- nil
- "banana"
Answer: "cherry". Negative indexes count from the end, so [-1] is the last element, "cherry".
What does [3, 1, 4, 1, 5].uniq return?
- [1, 3, 4, 5]
- [3, 1, 4, 5]
- [5, 1, 4, 1, 3]
- [3, 1, 4, 1, 5]
Answer: [3, 1, 4, 5]. uniq removes duplicates while preserving the order of first appearance: [3, 1, 4, 5].
Which method adds an element to the END of an array?
- unshift
- shift
- push
- pop
Answer: push. push (or <<) appends to the end; pop removes the last; shift/unshift work at the front.
What does [3, 1, 2].sort return?
- [3, 2, 1]
- [1, 2, 3]
- [3, 1, 2]
- [2, 1, 3]
Answer: [1, 2, 3]. sort returns a NEW ascending array [1, 2, 3] and leaves the original untouched.
Reading past the end of an array, like arr[99] on a 3-element array, returns what?
- An IndexError
- 0
- nil
- The last element
Answer: nil. Out-of-range index access returns nil rather than raising — check length first.
What does [1, 2, 3, 4, 5][1..3] return?
- [1, 2, 3]
- [2, 3, 4]
- [2, 3]
- [1, 2, 3, 4]
Answer: [2, 3, 4]. The range 1..3 is inclusive, grabbing indexes 1, 2, and 3: [2, 3, 4].
What does ["x", "y", "z"].join("-") produce?
- ["x", "y", "z"]
- "xyz"
- "x-y-z"
- "x, y, z"
Answer: "x-y-z". join glues elements into one string using the separator: "x-y-z".
What does [1, 2, 3, 4].sum return?
- 10
- 24
- 4
- [1, 2, 3, 4]
Answer: 10. sum adds all the elements: 1 + 2 + 3 + 4 = 10.
What is the difference between sort and sort!?
- sort! sorts descending; sort sorts ascending
- They are identical
- sort returns a new array; sort! mutates the array in place
- sort! is invalid Ruby
Answer: sort returns a new array; sort! mutates the array in place. The bang version sort! mutates the receiver; sort returns a new sorted array.
To clearly see an array's structure (brackets and quotes), you should use:
- puts arr
- print arr
- arr.inspect (or p arr)
- arr.to_s.length
Answer: arr.inspect (or p arr). inspect (and the p shortcut) show the array exactly as written in code, with brackets and quotes.
Continue this course
- Previous: Blocks
- Next: Hashes — Store and look up data with key-value pairs
- Quick reference: Ruby cheat sheet › Arrays & Hashes
Frequently asked questions
Why do array indexes start at 0 in Ruby?
Like most programming languages, Ruby uses zero-based indexing, so the first element is at index 0, the second at 1, and so on. This means the last index of an array of length n is n-1. Ruby also supports negative indexes that count from the end: arr[-1] is the last element and arr[-2] is the second-to-last. There are also friendly helpers — arr.first and arr.last — that avoid index arithmetic entirely.
What's the difference between push, <<, and pop?
push and the shovel operator << both add an element to the end of the array and modify it in place — arr << 4 and arr.push(4) are equivalent. pop does the opposite: it removes and returns the last element. There are mirror methods for the front of the array too: unshift (or prepend) adds to the start, and shift removes and returns the first element. Together they let you treat an array as a stack or a queue.
Does sort change the original array or return a new one?
sort returns a new sorted array and leaves the original untouched. If you want to sort the array in place, use the bang version sort!. This pattern is consistent across Ruby: methods like reverse, uniq, and map return new arrays, while their bang counterparts reverse!, uniq!, and map! mutate the receiver. Choosing the non-bang version is safer because it avoids surprising other code that shares the array.
What does inspect do, and why use it instead of puts?
puts on an array prints each element on its own line with no brackets, which makes it hard to see the structure. inspect returns a string showing the array exactly as you'd write it in code — with brackets, commas, and quotes around strings — so ["a", "b"] prints clearly. It's the go-to tool for debugging: puts arr.inspect (or the shortcut p arr) shows you precisely what the array contains, including nested arrays and nils.