Dominik Bathon
4/9/2005 5:43:00 PM
On Sat, 09 Apr 2005 18:26:15 +0200, Florian Groß <florgro@gmail.com> wrote:
> jzakiya@mail.com wrote:
>
>> array.last returns the value of the last array element.
>> In many instances it is necessary to get the index value
>> of the last array element. This is necessary in many
>> sorting and searching algorithms, especially where the
>> arrays are dynamically changing in size. You can do it like:
>> class Array
>> def last_index; self.length - 1 end
>> end
>> But this is slower than necessary, because array.last
>> already computes/knows what the last index value is,
>> and thus the mechanism already exists to get this info.
>> I would really like to see this method added to class Array.
>> It is a nice complement to Array#last, and aides performance.
>
> Can you not just use -1 as the index?
Here are some examples (in case you don't know how that works):
irb(main):083:0> [1, 2, 3, 4, 5][-1]
=> 5
irb(main):084:0> [1, 2, 3, 4, 5][-2]
=> 4
irb(main):085:0> [1, 2, 3, 4, 5][2..-1]
=> [3, 4, 5]
irb(main):086:0> [1, 2, 3, 4, 5][2..-2]
=> [3, 4]
And so on.
Dominik