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

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

    At least note that the behavior is consistent. From 5 on up everything acts the same; the weirdness only occurs at [4,N].

    Maybe this pattern helps, or maybe I'm just tired and it doesn't help at all.

    array[0,4] => [:peanut, :butter, :and, :jelly]
    array[1,3] => [:butter, :and, :jelly]
    array[2,2] => [:and, :jelly]
    array[3,1] => [:jelly]
    array[4,0] => []
    

    At [4,0], we catch the end of the array. I'd actually find it rather odd, as far as beauty in patterns go, if the last one returned nil. Because of a context like this, 4 is an acceptable option for the first parameter so that the empty array can be returned. Once we hit 5 and up, though, the method likely exits immediately by nature of being totally and completely out of bounds.

提交回复
热议问题