How does ruby handle array range accessing?

前端 未结 1 1896
再見小時候
再見小時候 2021-02-07 06: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 ou

1条回答
  •  一向
    一向 (楼主)
    2021-02-07 06:41

    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.

    0 讨论(0)
提交回复
热议问题