Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#fetch

(::int index) -> Elem
[T] (::int index, T default) -> (Elem | T)
[I < ::_ToInt, T] (I index) { (I index) -> T } -> (Elem | T)
fetch(index) → element
fetch(index, default_value) → element or default_value
fetch(index) {|index| ... } → element or block_return_value

Returns the element of self at offset index if index is in range; index must be an integer-convertible object.

With the single argument index and no block, returns the element at offset index:

Example
a = [:foo, 'bar', 2]
a.fetch(1)   # => "bar"
a.fetch(1.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 (which may be any object) and no block, returns default_value if index is out-of-range:

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

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"

Related: see Methods for Fetching.

See also #eql? #fetch_values #empty? #fill also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0