Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 134 ยท Collections

Arrays

Learn Ruby arrays - creating them, indexing and slicing, adding and removing elements, concat, flatten, compact, copies, and common errors, with runnable examples.

An array is an ordered list of objects. It is the collection you will use most in Ruby: lines read from a file, the results of a database query, the words of a sentence, the arguments of a command. Arrays can hold anything, including other arrays, and different types can be mixed in the same array. They grow and shrink as needed, and most of Ruby's collection methods (map, select, sort, and many more) are built to work with them.

This lesson covers the basics you need before the powerful iteration methods: creating arrays, reading elements by index and by range, adding and removing elements, combining arrays, nesting, copying (a place where beginners get surprised), and the errors you will meet. The next two lessons build on it with iteration and transformation and sorting and searching.

Creating arrays

The array literal uses square brackets. There are also shortcuts for arrays of words and symbols, and the Array class has constructors.

Ruby Ways to create an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • %w[...] builds an array of strings split on whitespace; %i[...] builds an array of symbols. Both save a lot of quotes and commas.
  • Array.new(3) makes three nils. Array.new(3, 0) fills with the same object. Array.new(4) { |i| ... } runs the block once per index and stores the results.
  • Kernel#Array converts "whatever you got" into an array: nil becomes [], an array stays as it is, a range or hash is expanded, and anything else is wrapped.

The shared-object trap

Array.new(3, []) puts the same inner array into every slot. Changing one changes all of them:

Ruby Array.new with a shared default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first result is [["x"], ["x"]] because both slots refer to one array. The block form creates a fresh object for every slot, which is almost always what you want for mutable defaults such as arrays, hashes and strings. Plain numbers and symbols are safe with the two-argument form.

Reading elements

Indexes start at 0. Negative indexes count from the end: -1 is the last element.

Ruby Indexing and slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two details to remember. First, a[5] for a five-element array is nil, because Ruby treats a missing element as nil rather than as an error. That leniency can hide bugs; use fetch when a missing index is a mistake. Second, slicing with a start index equal to the size gives [], while a start index beyond it gives nil. This is a historical detail of a[start, length] and a[range]; you rarely need it, but it explains puzzling nils. The lesson Slices and Indexing in Depth covers it fully.

fetch, dig and friends

Ruby fetch raises, [] returns nil (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

fetch(10) on a three-element array stops the program with index 10 outside of array bounds: -3...3 (IndexError). Give fetch a default value or a block to supply the answer instead. dig walks into nested arrays and returns nil as soon as something is missing, which is safer than nested[5][1] (that would raise NoMethodError on nil).

Changing an array

Arrays are mutable. Methods that change the receiver are the daily bread:

Ruby push, pop, shift, unshift, insert, delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

<< and push are the standard "add to the end" tools, and both are fast. shift and unshift work at the front; they are also efficient in Ruby, so an array can serve as a queue (more in Stacks, Queues and Other Structures). Assigning to an index beyond the end silently fills the gap with nil, which can create surprisingly large arrays if the index is wrong.

Many methods come in two versions: map returns a new array, map! changes the receiver. The bang versions of select!, reject! and uniq! return nil when nothing changed, so do not chain them. Prefer the non-bang version unless you really want to mutate.

Combining arrays

Ruby Plus, minus, intersection, union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

+ makes a new array; concat changes the first one in place. flatten removes all nesting levels unless you give it a depth, and compact removes nils (but not false). Set-like operators (&, |, -) are convenient for small arrays; for large ones use a Set.

Destructuring

Ruby can assign several variables from an array in one statement, with * collecting the rest:

Ruby Multiple assignment and splat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Swapping with x, y = y, x needs no temporary variable. The splat * also works the other direction, spreading an array into another array or into a method call.

Copies and aliases

Variables hold references to arrays. Assigning one variable to another does not copy anything:

Ruby Aliases, dup and deep copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

dup makes a shallow copy: a new outer array that still points to the same inner arrays. Changing shallow[0] changes nested[0] as well. For a deep copy of plain data, Marshal.load(Marshal.dump(x)) works; see Copying Objects. Freezing an array with freeze stops changes, and the error is clear:

Ruby Modifying a frozen array (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You see can't modify frozen Array: ["ada", "grace"] (FrozenError). Frozen arrays are good for constants (see Immutability and freeze). Note that freeze is shallow too: the strings inside can still change unless they are frozen separately.

Common errors

Ruby Type errors with arrays (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first three are rescued and print their messages: no implicit conversion of nil into Array, negative array size and String can't be coerced into Integer. The last line raises undefined method 'upcase' for nil (NoMethodError): the out-of-range index quietly returned nil, and the error appeared one step later. When you see NoMethodError for nil, look at the array access before it.

When to use arrays

Use an array when order matters and you mostly walk through the elements or index them by position. If you look things up by a key, use a Hash; if you only need membership and uniqueness, use a Set. For a few fields of fixed meaning, a Struct or Data object documents itself better than [name, age, city].

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [10, 20, 30][3] return?

    Reading an index outside the array with [] returns nil. Use fetch if you want an IndexError instead.
  2. 2. What is the result of [1, 2, 3, 4, 5][1..3]?

    The range 1..3 includes both ends, so indexes 1, 2 and 3 are returned.
  3. 3. After grid = Array.new(2, []) and grid[0] << 1, what does grid contain?

    Array.new(2, []) stores the same inner array twice, so the change shows in both slots. Use Array.new(2) { [] } for separate arrays.
  4. 4. Which method removes and returns the first element?

    shift removes and returns the first element. pop works on the last, unshift adds at the front and drop(1) returns a new array without changing the original.
  5. 5. Why does changing copy = original.dup; copy[0] << 1 also change original[0] when the elements are arrays?

    dup is shallow. The new outer array holds references to the same inner arrays.

Summary

  • Arrays are ordered, zero-indexed, growable lists; negative indexes count from the end.
  • Create them with literals, %w[], %i[], Array.new (use the block form for mutable defaults) and Array().
  • [] returns nil for a missing index; fetch raises IndexError or takes a default; dig handles nesting.
  • <</push, pop, shift, unshift, insert, delete, delete_at and concat change an array in place.
  • +, -, &, |, flatten and compact build new arrays.
  • Variables are references; dup is a shallow copy, freeze blocks changes.

Next: Iterating and Transforming Arrays