Martin DeMello wrote:
>
> "Trans" <transfire@gmail.com> schrieb im Newsbeitrag
> news:1113074095.070106.22910@l41g2000cwc.googlegroups.com...
> > > Can you not just use -1 as the index?
> >
> > No. Because, it is not always simply a matter of getting to the
last
> > element. If it were then #last itself would suffice. The use case
here
> > is when the last index is needed.
>
> Care to unveil the use case? I never neede that myself - just
> wondering...
I've written C code that started with a pointer at either end of an
array and walked them towards each other.
martin
Here's the source code from Array.c for Array#last:
static VALUE
rb_ary_last(argc, argv, ary)
int argc;
VALUE *argv;
VALUE ary;
{
if (argc == 0) {
if (RARRAY(ary)->len == 0) return Qnil;
return RARRAY(ary)->ptr[RARRAY(ary)->len-1];
}
else {
VALUE nv, result;
long n, i;
rb_scan_args(argc, argv, "01", &nv);
n = NUM2LONG(nv);
if (n > RARRAY(ary)->len) n = RARRAY(ary)->len;
result = rb_ary_new2(n);
for (i=RARRAY(ary)->len-n; n--; i++) {
rb_ary_push(result, RARRAY(ary)->ptr[i]);
}
return result;
}
}
Here's my modification of it to produce Array#last_index.
static VALUE
rb_ary_last_index(argc, argv, ary)
int argc;
VALUE *argv;
VALUE ary;
{
VALUE nv, result;
long n;
rb_scan_args(argc, argv, "01", &nv);
n = NUM2LONG(nv);
if (n > RARRAY(ary)->len) n = RARRAY(ary)->len;
return n;
}
Could someone verify/modify/test this to see if it works.
Jabari
···
Robert Klemme <bob.news@gmx.net> wrote: