1

For a four-element array, [4] returns nil, but [4, 0] returns an empty array.

array = [:peanut, :butter, :and, :jelly]
array[4] # => nil 
array[4, 0] # => [] 
array[5] # => nil 
array[5, 0] # => nil 

Why would [4, 0] not return nil just like [5, 0]?

Answer from Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com) => Graphical Explination of WHats Happening

uMinded
  • 595
  • 1
  • 9
  • 21

1 Answers1

3

It's a special case. From the official docs (the italics are mine):

For start and range cases the starting index is just before an element. Additionally, an empty array is returned when the starting index for an element range is at the end of the array.

a = [ "a", "b", "c", "d", "e" ]
# ...
# special cases
a[5]                   #=> nil
a[6, 1]                #=> nil
a[5, 1]                #=> []
Leo Brito
  • 2,053
  • 13
  • 20