Bug #7626
closedBizarre Array#fetch behavior with a block when index is out of bounds
Description
This also occurs on Ruby 1.8.
First, the example, taken almost directly from the docs (except the docs only describe the fetch(4) case):
irb(main):001:0> a = [11, 22, 33, 44]
=> [11, 22, 33, 44]
irb(main):002:0> a.fetch(0) { |i| i }
=> 11
irb(main):003:0> a.fetch(1) { |i| i }
=> 22
irb(main):004:0> a.fetch(2) { |i| i }
=> 33
irb(main):005:0> a.fetch(3) { |i| i }
=> 44
irb(main):006:0> a.fetch(4) { |i| i }
=> 4
This is incredibly bizarre and inconsistent behavior:
-
The docs suggest (but do not confirm) that the block should always be given the index
-
Without already having knowledge of whether the index is in or out of bounds, you can't differentiate between whether the block was given an index or a value. (Unless you can key off of type information)
-
What use case does the current behavior even solve?
It seems like the block should be given consistent arguments regardless of the index asked for: either the index (pointless), or the value (better) or both (best?). Or just deprecate this block behavior alltogether. Does anyone use it?