Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#values_at

array.values_at(*indexes) → new_array

Returns a new Array whose elements are the elements of self at the given Integer indexes.

For each positive index, returns the element at offset index:

Example
a = [:foo, 'bar', 2]
a.values_at(0, 2) # => [:foo, 2]

The given indexes may be in any order, and may repeat:

Example
a = [:foo, 'bar', 2]
a.values_at(2, 0, 1, 0, 2) # => [2, :foo, "bar", :foo, 2]

Assigns nil for an index that is too large:

Example
a = [:foo, 'bar', 2]
a.values_at(0, 3, 1, 3) # => [:foo, nil, "bar", nil]

Returns a new empty Array if no arguments given.

For each negative index, counts backward from the end of the array:

Example
a = [:foo, 'bar', 2]
a.values_at(-1, -3) # => [2, :foo]

Assigns nil for an index that is too small:

Example
a = [:foo, 'bar', 2]
a.values_at(0, -5, 1, -6, 2) # => [:foo, nil, "bar", nil, 2]

The given indexes may have a mixture of signs:

Example
a = [:foo, 'bar', 2]
a.values_at(0, -2, 1, -1) # => [:foo, "bar", "bar", 2]
See also #unshift #zip #uniq! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1