liveBook · Manning

Array#values_at

As explained in The Well-Grounded Rubyist, Fourth Edition

Hash#values_at is a Ruby Hash method that retrieves the values associated with multiple specified keys and returns them in an array.

Array#values_at extracts several elements by index in one operation and returns those values as a new array. Pass one or more index arguments rather than a contiguous range. section 9.2.2

Select several words

Given `array = %w(the dog ate the cat)`, `array.values_at(0, 3)` retrieves the two articles and assigns them to `articles`; printing it produces the selected values as an array.

Place values_at among Ruby's related element-retrieval operations:

  • Use `[index]` or `slice(index)` to retrieve one element. section 9.2.2
  • Use `dig` when the requested positions lead through nested arrays rather than selecting several positions from one array. section 9.2.2

The same method name also appears on Hash. There, the arguments are keys instead of integer indexes: `state_hash.values_at("New Jersey", "Delaware")` returns `["NJ", "DE"]`. section 9.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the method through syntax, a runnable example, and contrasts with indexing, ranges, slice, and dig.
Examples
Uses a sentence array to select the elements at indexes 0 and 3.
What it assumes
Assumes familiarity with arrays, zero-based indexing, method calls, and array literals.
What you can do after
Apply it via Ruby's Array#values_at to collect noncontiguous elements by index.
How it connects
Connects array indexing, slice, ranges, dig, and the Hash#values_at counterpart.

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.