liveBook · Manning

Slice

As explained in The Well-Grounded Rubyist, Fourth Edition

Array#slice is a Ruby Array method that retrieves elements specified by an index, an index and length, or a range.

Given an array of colors, `a.slice(3)` retrieves the element at index 3. `slice` is another name for the array’s `[]` retrieval method: use whichever reads more clearly where you need an element. section 9.2.2

The argument determines what comes back:

  • `a.slice(3)` retrieves one element. section 9.2.2
  • `a.slice(3, 2)` starts at index 3 and retrieves two elements in a new array. section 9.2.2
  • `a.slice(3..5)` retrieves the elements selected by the range, also in an array. section 9.2.2

A contiguous group

For `a = %w(red orange yellow purple gray indigo violet)`, `a.slice(3, 2)` returns `["purple", "gray"]`. The `3` is the starting index; the `2` is a length, not an ending index. section 9.2.2

Use `slice!` when the selected items should be removed from the array. For other retrieval jobs, `values_at` accepts multiple individual indexes, while `dig` follows indexes into nested arrays. Strings also have a `slice` method, but its arguments can specify substrings in additional ways. section 9.2.2 section 8.1.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains single-index, index-and-length, and range retrieval, but does not establish out-of-range behavior.
Examples
Uses a color array to show two-element and range retrieval alongside `[]` assignment.
What it assumes
Assumes basic familiarity with Ruby arrays and indexes; demonstrates length and range selection with small examples.
What you can do after
Apply it via Ruby’s `Array#slice` to retrieve one element or a contiguous group without removing it.
How it connects
Contrasts `Array#slice` with `Array#[]`, `Array#slice!`, `Array#values_at`, `Array#dig`, and `String#slice`.

Also explained in

Compare how 2 books explain slice →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.