Project

General

Profile

Actions

Bug #7626

closed

Bizarre Array#fetch behavior with a block when index is out of bounds

Added by Nevir (Ian MacLeod) almost 9 years ago. Updated almost 9 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin12.1.0]
Backport:
[ruby-core:51161]

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?

Actions

Also available in: Atom PDF