Feature #9948

Safely insert an object into an array

Added by sawa (Tsuyoshi Sawada) about 6 years ago. Updated about 1 year ago.

Target version:


When I insert an object using Array#insert(index, object) method (or Array#[index]= object), it happened sometimes that I mistakenly passed index that is too big, and too often in such cases was the bug very difficult to detect because in such case, insert will silently insert nil to fill up the empty slots:

[:foo, :bar].insert(4, :baz) # => [:foo, :bar, nil, nil, :baz]

On the other hand, when the index is too small (negative), index raises an index error. I wish that an error were raised when the index is too big (when index is greater than length of self), but it is perhaps a bad idea to change the feature of insert by now. So I propose that a new method being added, something like Array#safely_insert, which works the same as insert, except that when index is larger than the size of the array, it should raise:

Index Error: index #{indexs} too large for array; maximum: #{length}

Updated by nobu (Nobuyoshi Nakada) about 6 years ago

  • Description updated (diff)

"safely" sounds too vague.

Updated by sawa (Tsuyoshi Sawada) about 1 year ago

I withdraw this proposal. Please close it.


Updated by marcandre (Marc-Andre Lafortune) about 1 year ago

  • Status changed from Open to Closed

Also available in: Atom PDF