我有一些不再有效的 Ruby 代码,因为它假定所有越界数组范围访问都将返回空数组而不是 nil。
a = []
a[1..-1] == [] # code assumes this from ancient Ruby
a[1..-1] == nil # but gets this on newer Ruby >= 1.8
数组范围从不为零的 Ruby 最新版本是什么?
最佳答案
我认为是 1.2.x。
我能找到的最古老的 Ruby 文档是 Ruby 1.2 。它是这样描述 Array#[]
的:
self[start..end]
Returns an array containing the objects from start to end, including both ends. if end is laeger[sic] than the length of the array, it will be rounded to the length. And if start is larger than end, this method returns empty array (
[]
).
所以在 1.2 中,它总是返回一个数组。
我能找到的下一个最旧的文档 was for Ruby 1.6 。它说:
arr[anInteger] -> anObject or nil
arr[start, length] -> aSubArray or nil
arr[aRange] -> aSubArray or nilElement Reference-Returns the element at index anInteger, or returns a subarray starting at index start and continuing for length elements, or returns a subarray specified by aRange. Negative indices count backward from the end of the array (-1 is the last element). Returns
nil
if any indices are out of range.
这样就大大缩小了范围。然后我决定直接追根溯源。在 Ruby 1.2 中,Array#[]
称为 ary_aref
in array.c 。如果参数是一个范围,则调用 beg_len
获取起始索引和子序列的长度,然后调用 ary_subseq
与这些论点。长话短说,ary_subseq
总是返回一个数组,从不nil
。
接下来我尝试了 Ruby 1.3,其中 Array#[]
is now called rb_ary_aref
。你瞧,我们看到了这个( 406–414 ):
/* check if idx is Range */
switch (rb_range_beg_len(arg1, &beg, &len, RARRAY(ary)->len, 0)) {
case Qfalse:
break;
case Qnil:
return Qnil;
default:
return rb_ary_subary(ary, beg, len);
}
我认为这不言而喻:如果参数超出范围,则返回nil
。
由于我的 C 语言很糟糕,所以我检查了 Ruby 1.6 源代码(因为我们从文档中知道它具有 nil
行为)并发现 its implementation is the same .
我非常有信心,Ruby 1.2.x 是最后一个返回空数组的 Ruby,而 1.3.x 是第一个返回 nil
的 Ruby。
顺便说一句,Ruby 1.2 于 1998 年发布。
关于ruby - 数组范围从未返回 nil 的最后一个 Ruby 版本是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067465/