Slicing of arrays in ruby returns different result

2020-05-06 10:28发布

问题:

I'm puzzled by the fact that, if an array is sliced at it length, it returns an empty array, but at a length greater than that, it returns nil. What is the reason for this? For example:

arr = [1,2,3,4,5]

Doing this, where y > arr.length and x is any positive integer, returns nil:

arr[y, x] # => nil

but doing the following returns []

arr[5, x] # => []

Since arr[5] doesn't exist, shouldn't it return nil as well?

回答1:

It's all in the documentation: http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-5B-5D

Additionally, an empty array is returned when the starting index for an element range is at the end of the array.

Returns nil if the index (or starting index) are out of range.



标签: ruby arrays