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

后端 未结 10 2413
没有蜡笔的小新
没有蜡笔的小新 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 11:04

    An explanation provided by Jim Weirich

    One way to think about it is that index position 4 is at the very edge of the array. When asking for a slice, you return as much of the array that is left. So consider the array[2,10], array[3,10] and array[4,10] ... each returns the remaining bits of the end of the array: 2 elements, 1 element and 0 elements respectively. However, position 5 is clearly outside the array and not at the edge, so array[5,10] returns nil.

提交回复
热议问题