【基本介绍】
这里mark下ruby array遇到的一个问题
【简单
例子】
class="ruby" name="code">
irb(main):040:0> arr
=> [1, 2, 3, 4, 5]
irb(main):041:0> arr[5]
=> nil
irb(main):042:0> arr[5,0] #为什么不是nil?
=> []
irb(main):043:0> arr[6]
=> nil
irb(main):044:0> arr[6,0] #正常理解返回nil
=> nil
irb(main):045:0> arr.length
=> 5
问题:数组的index是从0-N,例子里面的最大下表应该是4,那问题为什么arr[5,0]返回不是nil而是[]
源码:
VALUE
rb_ary_aref(int argc, const VALUE *argv, VALUE ary)
{
VALUE arg;
long beg, len;
if (argc == 2) {
beg = NUM2LONG(argv[0]);
len = NUM2LONG(argv[1]);
if (beg < 0) {
beg += RARRAY_LEN(ary);
}
return rb_ary_subseq(ary, beg, len);
}
VALUE
rb_ary_subseq(VALUE ary, long beg, long len)
{
VALUE klass;
long alen = RARRAY_LEN(ary);
if (beg > alen) return Qnil;
if (beg < 0 || len < 0) return Qnil;
if (alen < len || alen < beg + len) {
len = alen - beg;
}
klass = rb_obj_class(ary);
if (len == 0) return ary_new(klass, 0);
return ary_make_partial(ary, klass, beg, len);
}
源码里面比较的begin与数组长度,比数组长的还回nil,否则还回数组片段。
【参考】
https://github.com/ruby/ruby/blob/trunk/array.c
http://stackoverflow.com/questions/3568222/array-slicing-in-ruby-looking-for-explanation-for-illogical-behaviour-taken-fr