简体   繁体   中英

Confusion about ruby Array [] method results when starting index greater than (array.size -1)

Given

array = [:a,:b,:c,:d] # with 4 elements:

array[3] => :d  # zero-based indices, I get that
array[4] => nil
array[5] => nil

array[3,0] => [] # OK since I asked for a slice with zero elements

Doco for array[start,length] says that it "Returns nil if the index (or starting index) are out of range."

array[5,0] => nil # OK
array[4,0] => []  # Hunh??

How come array[4,0] returns an array as opposed to nil ?

[edit] Looks like this has already come up: see Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

To me the explanation looks a bit like hand waving, but I'll settle for it and just accept that ruby violates PLS here.

I believe that the documentation does not word the behavior correctly. But intuitively, the bahavior makes sense. Just like it is possible to define a 0-element "sliver" at the beginning of the array, before all elements by indexing array[0,0] , it should also be possible, symmetrically, to get a 0-element "sliver" at the end of the array, after all the elements, by indexing array[array.size,0] . Another example would be that it should intuitively always be possible to get a copy of an array by indexing over its whole range, ie array[0,array.size] ; but this would not be possible for empty arrays if we returned nil when the starting index is equal to the array size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM