Array slicing in Ruby: explanation for illogical behaviour (taken from Rubykoans.com)

后端 未结 10 2406
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 10:39

I was going through the exercises in Ruby Koans and I was struck by the following Ruby quirk that I found really unexplainable:

array = [:peanut, :butter, :a         


        
10条回答
  •  一生所求
    2020-11-22 10:49

    I agree that this seems like strange behavior, but even the official documentation on Array#slice demonstrates the same behavior as in your example, in the "special cases" below:

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

    Unfortunately, even their description of Array#slice doesn't seem to offer any insight as to why it works this way:

    Element Reference—Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) are out of range.

提交回复
热议问题