ruby 如何处理数组范围访问?

发布于 2024-09-28 09:04:52 字数 172 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独夜无伴 2024-10-05 09:04:52

这是一个众所周知的丑陋奇怪的角落。查看 rdoc 中 Array#slice< 的示例/a>.

此特定问题被列为“特殊情况”。

   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。它已记录在案,但我不确定其原因。

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]               #=> []

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文