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 项数组的范围,为什么它们会返回不同的值?
ruby-1.8.7-p174 > [0,1][2..3]
=> []
ruby-1.8.7-p174 > [0,1][3..4]
=> nil
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个众所周知的丑陋奇怪的角落。查看 rdoc 中 Array#slice< 的示例/a>.
此特定问题被列为“特殊情况”。
如果起始位置恰好是数组末尾之外的一项,则它将返回一个空数组
[]
。如果开始时间超出此范围,则nil
。它已记录在案,但我不确定其原因。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"
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.