18
ruby-1.8.7-p174 > [0,1][2..3]
 => [] 
ruby-1.8.7-p174 > [0,1][3..4]
 => nil

In a 0-index setting where index 2, 3, and 4 are all in fact out of bounds of the 2-item array, why would these return different values?

Telemachus
  • 19,459
  • 7
  • 57
  • 79
Matt Humphrey
  • 225
  • 1
  • 2
  • 6
  • 3
    Your question has less noise, but unfortunately: possible duplicate of [Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)](http://stackoverflow.com/questions/3568222/array-slicing-in-ruby-looking-for-explanation-for-illogical-behaviour-taken-fr). In both cases the surprise is the same: nil vs [] at the end index. – Ciro Santilli OurBigBook.com Jan 28 '14 at 16:21
  • Wow, duplicate declined. Why? – Ciro Santilli OurBigBook.com Jan 30 '14 at 10:06
  • Good question. I raised a flag to ask to reevaluate or explain. I am curious to learn the reasoning of such. – pjvleeuwen Jan 14 '20 at 08:57

1 Answers1

29

This is a known ugly odd corner. Take a look at the examples in rdoc for Array#slice.

This specific issue is listed as a "special case"

   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[5, 1]                #=> []
   a[5..10]               #=> []

If the start is exactly one item beyond the end of the array, then it will return [], an empty array. If the start is beyond that, nil. It's documented, though I'm not sure of the reason for it.

Telemachus
  • 19,459
  • 7
  • 57
  • 79
  • See [this answer](https://stackoverflow.com/a/3568281/) and related comments where the difference is described in terms of 'fence-posting' and 'indexing'. I do agree with Ciro, this question is a duplicate. For those reading this Q&A, be aware that more details exist on the 'why' in that duplicate. – pjvleeuwen Jan 14 '20 at 08:48