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

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

    This makes sense when you consider than an array slice can be a valid lvalue, not just an rvalue:

    array = [:peanut, :butter, :and, :jelly]
    # replace 0 elements starting at index 5 (insert at end or array):
    array[4,0] = [:sandwich]
    # replace 0 elements starting at index 0 (insert at head of array):
    array[0,0] = [:make, :me, :a]
    # array is [:make, :me, :a, :peanut, :butter, :and, :jelly, :sandwich]
    
    # this is just like replacing existing elements:
    array[3, 4] = [:grilled, :cheese]
    # array is [:make, :me, :a, :grilled, :cheese, :sandwich]
    

    This wouldn't be possible if array[4,0] returned nil instead of []. However, array[5,0] returns nil because it's out of bounds (inserting after the 4th element of a 4-element array is meaningful, but inserting after the 5th element of a 4 element array is not).

    Read the slice syntax array[x,y] as "starting after x elements in array, select up to y elements". This is only meaningful if array has at least x elements.

提交回复
热议问题