0
array = [:peanut, :butter, :and, :jelly]

Why does array[4,0] return [] and array[5,0] returns nil?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Flavia
  • 563
  • 4
  • 9

1 Answers1

4

According to Array#[] documentation:

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.

a = [ "a", "b", "c", "d", "e" ]
a[2] +  a[0] + a[1]    #=> "cab"
a[6]                   #=> nil
a[1, 2]                #=> [ "b", "c" ]
a[1..3]                #=> [ "b", "c", "d" ]
a[4..7]                #=> [ "e" ]
a[6..10]               #=> nil
a[-3, 3]               #=> [ "c", "d", "e" ]
# special cases
a[5]                   #=> nil
a[6, 1]                #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []
falsetru
  • 357,413
  • 63
  • 732
  • 636