0

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?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186

1 Answers1

2

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.

Community
  • 1
  • 1
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367