Array.fetch

Signature

array.fetch(position)             #=> object

array.fetch(position) returns the object located at position. If position is outside array an IndexError is thrown. Note that if position is negative and outside of array then the index number reported in the exception will be reported as position - array.length. I’ve submitted a patch to fix it. If position is 0 or positive then start counting from the beginning of the array. If position is negative then start counting from the end of the array.

array.fetch(position, default)    #=> object

array.fetch(position, default) returns the object located at position. If position is outside of array then default is returned. If position is 0 or positive then start counting from the beginning of the array. If position is negative then start counting from the end of the array.

array.fetch(position) {|position| block}  #=> object

array.fetch(position) {|position| block} returns the object located at position. If position is outside of array then block’s returned results is returned. If position is 0 or positive then start counting from the beginning of the array. If position is negative then start counting from the end of the array.

Examples

a = ['a','b','c','d','e','f']   #=> ["a", "b", "c", "d", "e", "f"]
a.fetch(2)                      #=> "c"
a.fetch(-2)                     #=> "e"

begin
  a.fetch(99)
rescue Exception => e
  e.inspect                     #=> "#<IndexError: index 99 out of array>"
end

begin
  a.fetch(-99)
rescue Exception => e
  # Note that it reports an index of -93 (i.e. -99 - a.length).
  e.inspect                     #=> "#<IndexError: index -93 out of array>"
end


begin
  a.fetch(-7)
rescue Exception => e
  # Note that it reports an index of -1 (i.e. -7 - a.length).
  e.inspect                     #=> "#<IndexError: index -1 out of array>"
end


a.fetch(4, 'z')                 #=> "e"
a.fetch(99, 'z')                #=> "z"

a.fetch(4){false}               #=> "e"
a.fetch(99){false}              #=> false

def default_fetch(ary, position)
  element = nil
  if position > ary.length
    element = ary.last
  else
    element = ary.first
  end
end

a.fetch(99){|position| default_fetch(a, position)}    #=> "f"
a.fetch(4){|position| default_fetch(a, position)}     #=> "e"
a.fetch(-99){|position| default_fetch(a, position)}   #=> "a"

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.fetch