Array#last and Array#first should accept negative arguments relative to the end of the Array.
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.
Array#[]. (Add the length of the Array to it to make it relative to the end of the Array.)
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.)
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
-- matz.
-- Jamis
I think it makes sense to think about the argument as an amount of values you're asking for which can be relative to the total amount of values available.
-- flgr
I couldn't see any reason for your "should". Can you show us why do you think they should be no distinction? I feel offsets and number of items are different, even though they are related (e.g. 0 .. number of items = range for those items). When I describe the "first(n)" method, it should be: "retrieve first n items from the array"; not "retrive items from offset zero to offset n (including n)", which makes me somewhat confusing.
- matz.
I think I see what you're getting at -- so this is about not exposing features of underlying implementations, because the underlying implementation might change and make it harder to make those features available?
I still think this would a nice compromise between another pair of methods and not having the features they would offer at all without introducing any icky flags and the like, but I think I can understand if you choose to reject this because of the above reason. (Though it would be a bit sad.)
-- flgr
-- matz.
Back to RCRchive.
RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog