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) over 11 years ago. Updated over 11 years ago.

Status:
Rejected
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?

Updated by marcandre (Marc-Andre Lafortune) over 11 years ago

  • Status changed from Open to Rejected

fetch(val){block} either returns the requested value or yields to the block and return that result. The block is thus called only if the requested index is out of range and the argument is always the index.

Updated by Nevir (Ian MacLeod) over 11 years ago

Why would you need to call fetch with a block if you already know the index is out of range? You already have the index you're calling with...

Updated by Nevir (Ian MacLeod) over 11 years ago

Oh! It's a block form of default - I get it now. Disregard!

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0