Explain it simply
Explain it simply
An array is an ordered list of things, like a numbered shopping list stuck to the fridge. Each item has a position called an index, and Ruby counts positions from 0, so the first item is at index 0, the second at index 1, and so on. The list can hold any kind of value, and it grows by itself when you add items.
Most Ruby programs are really about lists: the users on a page, the lines of a file, the scores in a game. Arrays come with a large toolbox, so instead of writing loops by hand you usually ask the array to map, select or sort itself and get the answer back as a new array.
Problem → Why → Solution
The problem: the backup list changes along with the original
Suppose you keep a list of fruit and want a backup copy before you change it. You write backup = original, add a new fruit to original, and then print backup expecting the old list. The new fruit shows up in both, and your backup was never a backup at all.
There is a second, quieter trap: asking for an item that is not there. Ruby does not raise an error for fruits[10]; it silently gives you nil, and the crash only arrives later when some other line calls a method on that nil.
original = ["Apple", "Banana"]
backup = original # looks like a copy, but it is the same array
original << "Cherry"
p backup # ["Apple", "Banana", "Cherry"], not the old listWhy does the backup change?
A variable does not contain the array; it points at it. Assigning backup = original copies the pointer, so both names lead to one array in memory, and a change made through either name is visible through the other. To get an independent list you have to ask for a copy explicitly, and once you know where the pointers are, bugs like this become easy to predict.
Core concept: numbered slots and name tags
An array is written with square brackets, [10, 20, 30], and %w[red green blue] is a shortcut for an array of strings without quotes and commas. The first item has index 0. Negative indexes count from the end, so list[-1] is the last item and list[-2] the one before it. The methods first and last give the same items with clearer names, and first(2) or last(2) return the first or last two items as a new array.
Reading outside the array does not raise an error: list[10] and list[-10] both return nil. That convenience is also a trap, because the nil travels onward until something calls a method on it and Ruby raises NoMethodError. When a missing item is a bug, use fetch, which raises IndexError (on a four-item array: index 10 outside of array bounds: -4...4) or returns a default value you supply.
To change an array, << and push add an item at the end, pop removes the last item, shift removes the first, and unshift adds at the front. The table shows the everyday tools for building a new list from an old one. None of them changes the original array.
| Task | Method | Returns |
|---|---|---|
| Change every item | map { |item| ... } | New array of the block's results |
| Keep matching items | select { |item| ... } | New array of items where the block is true |
| Drop matching items | reject { |item| ... } | New array without those items |
| Order by a key | sort_by { |item| key } | New array sorted by that key |
Beginners often reach for each when they need map. each runs the block for its side effects and returns the original array, so [1, 2, 3].each { |n| n * 2 } still gives [1, 2, 3]. Use map when you want the results back as a list. Remember too that methods ending in ! (map!, sort!) change the receiving array in place.
Finally, a variable holds a reference to an array. b = a gives two names for one array, so changes through either are shared. a.dup creates a new outer array with the same items, which is enough for flat lists, but it is shallow: nested arrays and strings inside are still shared between the two copies.
- Slots are numbered from 0
- Negative numbers count from the end
- Past the end gives nil
- Names point at the array, not copy it
Picture an array as a row of numbered boxes, and variables as name tags pointing at that row; the tags do not copy the row.
General pattern
list = [item, item, item] # create an array
list[index] # read one item (negative counts from the end)
list << item # append an item (changes list)
list.map { |item| new_value } # new array of block results
list.select { |item| condition } # new array of matching items
list.sort_by { |item| sort_key } # new array ordered by the key
copy = list.dup # shallow copy, not an aliasApart from <<, these methods return a new array and leave the original list alone. copy = list.dup makes the outer array independent, but the items inside are still shared.
Example: building and reading a fruit list
This program builds a short fruit list, adds an item, reads items from both ends and numbers the list. The last two lines show what a negative index and an out-of-range index return; they use p so that nil is visible, whereas puts nil would print an empty line.
fruits = ["Apple", "Banana", "Cherry"]
puts fruits[0]
fruits << "Durian"
puts fruits.last
puts "Total fruits: #{fruits.length}"
fruits.each_with_index do |fruit, index|
puts "#{index + 1}. #{fruit}"
end
p fruits[-2]
p fruits[10]Code breakdown
- Create
fruits = ["Apple", "Banana", "Cherry"]The array is created with three items sitting at indexes 0, 1 and 2, which is why the last index is one less than the length.
- Read by index
puts fruits[0]Index 0 is the first item, so this prints Apple. Using [] only reads; it does not change the array.
- Append
fruits << "Durian"<< appends an item at the end and changes fruits in place. From this line on the array has four items.
- Last item
puts fruits.lastlast gives the final item without you knowing the length, so it prints Durian, the item just added.
- Index and item
fruits.each_with_index do |fruit, index|each_with_index hands the block both the item and its position. The index starts at 0, so the program prints index + 1 to give people friendly numbers.
- Negative index
p fruits[-2]-2 counts from the end, so it returns the second-to-last item, "Cherry". p prints in inspect form, which is why the quotes appear.
- Out of range
p fruits[10]There is no item at index 10, so Ruby returns nil instead of raising. If that nil is used later, a NoMethodError can appear far from the real cause.
Apple
Durian
Total fruits: 4
1. Apple
2. Banana
3. Cherry
4. Durian
"Cherry"
nilmap, select, reject and sort_by
These methods return a new array, so you can chain one after another. In the code below, a list of scores is doubled, split into passing and failing, and given a 10-point bonus that is capped at 100. The second half sorts an array of pairs by age and by name with sort_by.
scores = [72, 95, 58, 88, 41]
doubled = scores.map { |score| score * 2 }
passing = scores.select { |score| score >= 60 }
failing = scores.reject { |score| score >= 60 }
capped = scores.map { |score| [score + 10, 100].min }
p doubled
p passing
p failing
p capped
p scores
people = [["Mya", 29], ["Aung", 34], ["Zaw", 21]]
p people.sort_by { |name, age| age }
p people.sort_by { |name, age| name }.map(&:first)
p people.map { |name, age| age }.sumThe values printed are [144, 190, 116, 176, 82], [72, 95, 88], [58, 41], [82, 100, 68, 98, 51], [72, 95, 58, 88, 41], [["Zaw", 21], ["Mya", 29], ["Aung", 34]], ["Aung", "Mya", "Zaw"] and 84. Look at the fifth output: scores is exactly as it was, because these methods only build new arrays.
Aliases, dup and shallow copies
In the diagram below there are three names and two arrays. original and alias_name point at the same array, while copy points at a separate array made by dup.
Names and arrays
----------------
original ---+
+--> [ "Apple", "Banana", "Cherry" ]
alias_name -+
copy -----------> [ "Apple", "Banana" ] (made by dup before the change)original = ["Apple", "Banana"]
alias_name = original
copy = original.dup
original << "Cherry"
p alias_name
p copy
p alias_name.equal?(original)
p copy.equal?(original)
nested = [["x"], ["y"]]
shallow = nested.dup
shallow[0] << "!"
p nested
independent = nested.map(&:dup)
independent[1] << "?"
p nested
p independentThe first half prints ["Apple", "Banana", "Cherry"], ["Apple", "Banana"], true and false; equal? asks whether two names point at the very same object. With nested arrays, even after dup, shallow[0] << "!" changes nested too, because the inner ["x"] is shared. Only copying the inner arrays as well, as nested.map(&:dup) does, makes them independent.
Safe reads and the Array.new trap
Choose how to read based on whether a missing item is a bug: [] gives nil, while fetch gives a default or raises. It is also worth knowing what first, sum and max return on an empty array. The last part compares Array.new(2, []) with the block form.
queue = ["a", "b"]
p queue[5]
p queue.fetch(5, "none")
begin
queue.fetch(5)
rescue IndexError => e
puts e.message
end
p [].first
p [].sum
p [].max
shared = Array.new(2, [])
shared[0] << 1
p shared
separate = Array.new(2) { [] }
separate[0] << 1
p separateThe output is nil, "none", index 5 outside of array bounds: -2...2, nil, 0, nil, [[1], [1]] and [[1], []]. With Array.new(2, []) both slots share one inner array, so adding to one shows up in both. The block form Array.new(2) { [] } builds a fresh array for each slot.
In real projects
Where this shows up in real projects
Arrays are the shape most data arrives in. A database query gives you a list of records, a JSON API returns an array of objects, a CSV file becomes an array of rows, and a text file read line by line becomes an array of strings. A line such as orders.select(&:paid?).map(&:total).sum, run on a list of order objects, reads almost like a sentence, and you will meet the same select, map and sort_by pipeline in scripts, tests and background jobs.
Aliasing matters in real systems too. A constant list such as STATUSES = %w[draft published].freeze is usually frozen so no method can change it by accident, and a method that receives an array should not mutate it unless its name says so (with a !). When a function returns a modified list without touching its argument, you can call it in tests and in many places without surprises.
Common mistakes
Common mistakes
1. Using each when you need map
doubled = [1, 2, 3].each { |n| n * 2 } stores [1, 2, 3], not [2, 4, 6], because each returns the original array. Use map when you want the results as a list, and keep each for side effects such as printing.
2. Treating b = a as a copy
After b = a and b << 3, a has become [1, 2, 3] too. Use a.dup when you need your own list, and copy the inner arrays as well, for example with a.map(&:dup), when there are nested arrays; otherwise both sides keep sharing them.
3. Calling a method on an out-of-range item
fruits[10].upcase raises NoMethodError (undefined method 'upcase' for nil) because fruits[10] is nil. Notice that the error appears at the method call, not at the read. When the item must exist, use fetch so the missing item is caught immediately.
4. The shared array in Array.new(3, [])
Array.new(3, []) fills all three slots with the same inner array, so grid[0] << 1 makes 1 appear in every row. Use the block form Array.new(3) { [] } so each slot gets its own array.
Best practices
Best practices
- Prefer map, select and reject over hand-written index loops; they read better and avoid off-by-one mistakes.
- Give arrays plural names such as fruits or scores, so a single item can be called fruit or score.
- Use fetch instead of [] where an item must exist, so a missing one is caught immediately.
- Let methods return a new array instead of changing their argument, and freeze constant lists.
Mini challenge
Mini challenge: reading-list helpers
Write three methods that work on a reading list of [title, pages] pairs. No method may change the original list; they return new results instead.
- titles_up_to(books, max_pages) returns the titles of books with at most max_pages pages, ordered from fewest pages to most
- with_book(books, title, pages) returns a new array that includes the extra book and leaves books unchanged
- longest_title(books) returns the title of the book with the most pages, or nil for an empty list
- Use methods such as map, select and sort_by instead of index loops
def titles_up_to(books, max_pages)
# TODO: keep short books, order them by pages, return only the titles
end
def with_book(books, title, pages)
# TODO: return a NEW array; do not change books
end
def longest_title(books)
# TODO: title of the book with the most pages (nil when the list is empty)
end
books = [["Ruby Basics", 120], ["Web Apps", 340], ["Testing", 90], ["Design", 210]]
# TODO: print the short titles, the sizes before and after adding a book, the longest
# title, and the longest title of an empty list with pExpected: Testing, Ruby Basics 4 -> 5 books Longest: Rails nil
Show hint
Chain select, then sort_by, then map. You can split block parameters as |title, pages|, and a parameter you do not use may start with an underscore. max_by returns nil on an empty array, and &.first passes that nil through.
Show solution
def titles_up_to(books, max_pages)
books.select { |_title, pages| pages <= max_pages }
.sort_by { |_title, pages| pages }
.map { |title, _pages| title }
end
def with_book(books, title, pages)
books + [[title, pages]]
end
def longest_title(books)
books.max_by { |_title, pages| pages }&.first
end
books = [["Ruby Basics", 120], ["Web Apps", 340], ["Testing", 90], ["Design", 210]]
bigger = with_book(books, "Rails", 400)
puts titles_up_to(books, 150).join(", ")
puts "#{books.size} -> #{bigger.size} books"
puts "Longest: #{longest_title(bigger)}"
p longest_title([])Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Array indexes start at 0, negative indexes count from the end, and reading past the end returns nil instead of raising.
- << and push change the array in place, while map, select, reject and sort_by return new arrays.
- each returns the original array and map returns the results, so use map when you need them.
- b = a gives two names for one array; dup makes a shallow copy whose nested items are still shared.
Official Ruby Documentation — Ruby Documentation