Ruby Method of the Day - 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
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
Trackbacks
Use the following link to trackback from your own site:
http://drotner.org/articles/trackback/71
