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

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

    Slicing and indexing are two different operations, and inferring the behaviour of one from the other is where your problem lies.

    The first argument in slice identifies not the element but the places between elements, defining spans (and not elements themselves):

      :peanut   :butter   :and   :jelly
    0         1         2      3        4
    

    4 is still within the array, just barely; if you request 0 elements, you get the empty end of the array. But there is no index 5, so you can't slice from there.

    When you do index (like array[4]), you are pointing at elements themselves, so the indices only go from 0 to 3.

提交回复
热议问题