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

时间:2021-04-25 16:40:09
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?

在0索引设置中,索引2、3和4实际上都超出了2项数组的范围,为什么这些值会返回不同的值?

1 个解决方案

#1


26  

This is a known ugly odd corner. Take a look at the examples in rdoc for Array#slice.

这是一个众所周知的丑陋古怪的角落。看看rdoc中用于数组#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.

如果start恰好是数组末尾的一个项目,那么它将返回[],一个空数组。如果开始超过这个,则为nil。这是有记录的,虽然我不确定原因。

#1


26  

This is a known ugly odd corner. Take a look at the examples in rdoc for Array#slice.

这是一个众所周知的丑陋古怪的角落。看看rdoc中用于数组#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.

如果start恰好是数组末尾的一个项目,那么它将返回[],一个空数组。如果开始超过这个,则为nil。这是有记录的,虽然我不确定原因。