Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 134 ยท Collections

Slices and Indexing in Depth

Master Ruby array and string indexing - negative indices, ranges as indexes, start and length slices, slice!, values_at, fetch, fetch_values and dig, with runnable examples.

Reading part of an array looks simple: list[0]. But Ruby offers a whole family of ways to reach into a collection, and the details decide whether your code returns a value, returns nil, raises an error or quietly changes your data. Knowing the rules exactly is what separates "it works on my example" from "it works on every input".

This lesson covers the index forms for arrays (and, because they share the same rules, strings): negative indices, the start and length form, ranges as indexes including endless and beginless ones, the destructive slice!, plus values_at, fetch, fetch_values and dig for safe access. You should know Arrays and Ranges first.

One element: positive and negative indices

An integer index picks one element. Counting starts at 0 from the front. A negative index counts from the back, so -1 is the last element.

Ruby Single element access

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.

An index outside the array does not raise an error: letters[5] and letters[-6] return nil. That convenience hides a trap, because nil can also be a legitimate stored value. When "missing" must be different from "stored nil", use fetch (shown below).

Start and length: array[start, length]

With two integers, Ruby returns a new array with length elements beginning at start. The start can be negative too.

Ruby Start and length

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.

Look at the middle three results. nums[3, 10] asks for more than exists and simply returns what is there. nums[5, 3] starts exactly one past the end and returns an empty array [], while nums[6, 3] starts beyond that and returns nil. This odd-looking rule makes sense when you think of indices as positions between elements: the position right after the last element is valid (nothing sits there yet, so the slice is empty), but anything farther away does not exist.

The same boundary rule means array[array.size, n] is always []. That is why loops that peel off the tail with array[i, n] end cleanly without extra checks.

Ranges as indexes

A range selects from its start to its end. Inclusive (..) and exclusive (...) both work, and negative numbers count from the back.

Ruby Slicing with ranges

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.

An endless range (-3..) means "to the end" and a beginless one (..2) means "from the start". They read much better than the older nums[-3..-1] and nums[0..2]. The out-of-range behaviour matches the start-and-length form: a start equal to size gives [], a start beyond it gives nil.

A line that ends with an endless range swallows the next line as its end: tail = 10.. followed by puts tail is read as 10..puts(tail). When you assign an endless range, wrap it in parentheses: tail = (10..). Inside brackets (nums[3..]) there is no problem because the closing bracket ends the range.

Ranges can also be stepped with % or step to take every n-th element: (0..8) % 2 yields 0, 2, 4, 6, 8, and nums.values_at(*(0...nums.size).step(2)) picks every second element.

Slicing strings the same way

Strings use the same forms and the same rules, with characters instead of elements. Strings also accept a substring or a regular expression as the index.

Ruby The same rules on strings

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.

word[11] is nil (no character there) but word[11, 2] is the empty string "" (the position after the last character), and word[12, 2] is nil. Looking up a substring returns it if present and nil otherwise, which makes word["gram"] a compact "contains and give me the text" test. See String Methods for more.

Changing slices: assignment and slice!

The bracket forms also work on the left of =. Assigning to a slice replaces that part, and the replacement may have a different length, so the array can grow or shrink.

Ruby Assigning to slices

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.

Replacing with an empty array deletes the slice. Replacing a length-zero slice (list[2, 0] = ...) inserts at that position without removing anything. These are two of the most useful tricks in the whole language.

slice! is the remove and return version. It cuts the part out of the array and gives it back to you, leaving the rest in place.

Ruby slice! cuts and returns

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.

Plain slice (with no bang) is the same as []: it copies and leaves the array alone. Use slice! for batching, as in a loop of until list.empty?; batch = list.slice!(0, 100); ...; end. For large lists, remember that removing from the front shifts everything behind it, so for millions of elements prefer each_slice or an index.

Several positions at once: values_at

values_at picks arbitrary positions in the order you give them. It accepts integers and ranges, and positions that do not exist produce nil, in the right slot.

Ruby values_at

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 same result with brackets would need several expressions. It is also a tidy way to reorder: row.values_at(1, 0) swaps the first two. Hashes have their own values_at, and fetch_values (below) is its strict relative.

Safe access: fetch, fetch_values and dig

array[i] answers nil for a missing index. fetch is the strict version: it raises when the index is out of range, unless you give a default or a block.

Ruby fetch with default and block

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(1) correctly returns the stored nil, which you could not tell apart from "missing" with prices[1]. A block default is only run when needed, so it can be expensive or print a message without penalty on the hit path. Now the strict failure, which you want in tests and in code that must not guess:

Ruby fetch on a missing index (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.

Ruby stops with index 7 outside of array bounds: -3...3 (IndexError). The message even states the valid range. For a hash, fetch raises a KeyError such as key not found: "color".

For nested data (arrays inside hashes inside arrays), writing data[:users][0][:name] crashes with NoMethodError the moment one level is nil. dig walks the path and returns nil as soon as something is missing.

Ruby dig through nested data

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.

dig works on arrays, hashes and Structs (any object that defines dig). It is the idiomatic answer to JSON-shaped data, but if a missing path means a bug, prefer fetch calls (chained, or dig plus a check) so the program fails near the cause rather than passing nil along. See Hashes for fetch and dig on hashes and Ternary, Safe Navigation and Short-Circuit for &..

Quick reference

Form Result
a[i] one element or nil
a[start, len] new array; [] at size, nil beyond
a[range] new array; endless/beginless allowed
a.values_at(...) picks listed positions, nil for missing
a.slice!(...) removes and returns the slice
a.fetch(i) element or IndexError; default or block allowed
a.dig(i, ...) walks nested structures, nil if absent

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

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

    The start index equals the array size, which is the valid position just past the last element, so the slice is an empty array. A start of 4 would return nil.
  2. 2. Which expression returns the last three elements of an array a?

    An endless range starting at -3 runs from the third-from-last element to the end. a[..-3] would return everything up to the third from last.
  3. 3. How is fetch different from [] for an index that does not exist?

    fetch is the strict lookup. It is also the only way to tell a missing index from a stored nil.
  4. 4. What is the effect of list[2, 0] = [:x, :y]?

    Assigning to a zero-length slice inserts the new elements at that position.
  5. 5. What does slice!(0, 3) do?

    The bang version both mutates the array and returns the removed part. Plain slice only copies.

Summary

  • Indexes start at 0 and negative indexes count from the back; a missing single index gives nil.
  • a[start, len] and a[range] return new arrays. A start equal to size gives []; a start beyond it gives nil.
  • Endless (a[2..]) and beginless (a[..2]) ranges are the clearest way to slice to the edges; parenthesize endless ranges when you assign them.
  • Strings follow the same rules and also accept substrings and regular expressions.
  • Assigning to a slice replaces it (empty array deletes, zero length inserts); slice! removes and returns.
  • values_at picks several positions; fetch and fetch_values fail loudly; dig walks nested data and returns nil safely.

Next: Stacks, Queues and Other Structures