Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method · added in Ruby 3.4

Array#fetch_values

(*::int indexes) -> self
fetch_values(*indexes) → new_array
fetch_values(*indexes) { |index| ... } → new_array

With no block given, returns a new array containing the elements of self at the offsets specified by indexes. Each of the indexes must be an integer-convertible object:

Example
a = [:foo, :bar, :baz]
a.fetch_values(2, 0)   # => [:baz, :foo]
a.fetch_values(2.1, 0) # => [:baz, :foo]
a.fetch_values         # => []

For a negative index, counts backwards from the end of the array:

Example
a.fetch_values(-2, -1) # [:bar, :baz]

When no block is given, raises an exception if any index is out of range.

With a block given, for each index:

  • If the index is in range, uses an element of self (as above).

  • Otherwise, calls the block with the index and uses the block’s return value.

Example:

Example
a = [:foo, :bar, :baz]
a.fetch_values(1, 0, 42, 777) { |index| index.to_s }
# => [:bar, :foo, "42", "777"]

Related: see Methods for Fetching.

Ruby version changes

  1. 3.4
See also #fetch #fill #eql? #filter also in 4.1 · 4.0