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#fetch

array.fetch(index) → element
array.fetch(index, default_value) → element
array.fetch(index) {|index| ... } → element

Returns the element at offset index.

With the single Integer argument index, returns the element at offset index:

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

If index is negative, counts from the end of the array:

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

With arguments index and default_value, returns the element at offset index if index is in range, otherwise returns default_value:

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

With argument index and a block, returns the element at offset index if index is in range (and the block is not called); otherwise calls the block with index and returns its return value:

Example
a = [:foo, 'bar', 2]
a.fetch(1) {|index| raise 'Cannot happen' } # => "bar"
a.fetch(50) {|index| "Value for #{index}" } # => "Value for 50"
See also #eql? #fill #empty? #filter also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1