Editing Topic: RCR204 Project: RCR | RCRchive home

RCR 204: Negative arg for Array#first and

submitted by flgr on Thu Jan 29 2004 12:48:58 PM -0800

Status: pending


Abstract

Array#last and Array#first should accept negative arguments relative to the end of the Array.

Problem

Currently Array#[] and Array#last / Array#first are inconsistent in their handling of negative arguments. It would be expected for both of them to work analogous in this case.

Proposal

Handle a negative argument to these constructs just like in Array#[]. (Add the length of the Array to it to make it relative to the end of the Array.)

Analysis

This would also add the rest() function of LISP (which was already wanted by some in the standard Ruby in the past) by generalising something which is already there.

There would be no incompatibilities caused by this because negative lengths previously had no meaning in this construct. (They used to raise an exception.)

Implementation

class Array
  def first(amount = 1); self[0 ... amount]; end
  def last(amount = 1); self[-amount .. -1]; end
end

if __FILE__ == $0
  ary = [1, 2, 3, 4, 5]
  p ary.first(2)
  p ary.last(-2)
end


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog