How does ruby handle array range accessing?

2019-03-24 13:11发布

问题:

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?

回答1:

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.