ruby 如何处理数组范围访问? [英] How does ruby handle array range accessing?
本文介绍了ruby 如何处理数组范围访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ruby-1.8.7-p174 > [0,1][2..3]
=> []
ruby-1.8.7-p174 > [0,1][3..4]
=> nil
在 0 索引设置中,索引 2、3 和 4 实际上都超出了 2 项数组的范围,为什么它们会返回不同的值?
In a 0-index setting where index 2, 3, and 4 are all in fact out of bounds of the 2-item array, why would these return different values?
推荐答案
这是一个众所周知的丑陋怪角.查看 rdoc 中 Array#slice<的示例/a>.
This is a known ugly odd corner. Take a look at the examples in rdoc for Array#slice.
这个特定问题被列为特殊情况"
This specific issue is listed as a "special case"
a = [ "a", "b", "c", "d", "e" ]
a[2] + a[0] + a[1] #=> "cab"
a[6] #=> nil
a[1, 2] #=> [ "b", "c" ]
a[1..3] #=> [ "b", "c", "d" ]
a[4..7] #=> [ "e" ]
a[6..10] #=> nil
a[-3, 3] #=> [ "c", "d", "e" ]
# special cases
a[5] #=> nil
a[5, 1] #=> []
a[5..10] #=> []
如果开始是恰好在数组末尾之外的一项,那么它将返回[]
,一个空数组.如果开始超出此范围,则 nil
.它已记录在案,但我不确定其原因.
If the start is exactly one item beyond the end of the array, then it will return []
, an empty array. If the start is beyond that, nil
. It's documented, though I'm not sure of the reason for it.
这篇关于ruby 如何处理数组范围访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文