0

I'm stuck trying to understand the following:

%w[a b c d][4,20] => []
%w[a b c d][4] => nil
%w[a b c d][5,20] => nil
  1. Why is there the added index on the tail end of the Array?
  2. Why does slice return different results? Is 4 not out of range? Seems inconsistent, but I think #1 will shed a bit of light on the answer to this question.
Eric M.
  • 5,399
  • 6
  • 41
  • 67
  • 1
    Read the [docs](http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-5B-5D), Luke! Difference between `ar[4]` and `ar[4,1]` from your example is also mentioned there (as a special case). – KL-7 Jun 20 '12 at 15:18
  • Thanks. I need to brush up on my C. I understand that it's a special case, but don't understand why or the purpose of it. Why is ar[4,1] in range, but not ar[5,1]. The latter makes sense to me, the former does not. – Eric M. Jun 20 '12 at 15:27
  • I guess Matz thinks it makes sense. See [this](http://stackoverflow.com/a/3219311/357743) explanation. Or [this](http://stackoverflow.com/a/3568281/357743) one. – KL-7 Jun 20 '12 at 15:31

1 Answers1

1

Exactly as KL-7 said, passing the index (or starting index for a slice) as one past the end of the array is treated as a special case. A slice starting at one past the last element will always return [].

I don't think there is a purpose for this, seems to be just a side effect of how the rb_ary_subseq function within Ruby is coded (it does a start > len check instead of a start >= len).

robbrit
  • 17,560
  • 4
  • 48
  • 68