4

I noticed a strange behavior when Range are used as Array subscript. (At least it's strange for me.)

a = [1,2,3]
=> [1, 2, 3]
a[3]
=> nil
a[3..-1]
=> []
a[4]
=> nil
a[4..-1]
=> nil

I thought a[3..-1] returns nil, but somehow it returns []. a[-3..-4] also returns [].

Could anyone explain why it returns [], when I use marginal values of range?

ironsand
  • 14,329
  • 17
  • 83
  • 176
  • 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) – Nakilon Dec 23 '14 at 06:42

1 Answers1

4

Because when range.begin == array.length, it always returns []. This is noted as a "special case" in the Ruby documentation:

a = [ "a", "b", "c", "d", "e" ]
# special cases
a[5]                   #=> nil
a[6, 1]                #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Thanks, I didn't notice there is a note in the documentation. May I ask why this case are treated as special? – ironsand Dec 19 '14 at 14:12
  • 1
    @Tetsu, it's just a convenience, to allow you to do certain things more easily. For example, suppose you wanted to write a method `m` that returned an array containing the last `n` elements of a given array, for `0 <= n <= arr.size`. You could write `def m(arr,n) arr[arr.size-n..-1] end`, without having to treat `n = 0` as a special case. Ruby is littered with such special cases, all to make your life easier and better. The Ruby monks really do have your interest at heart. – Cary Swoveland Dec 19 '14 at 15:11
  • Ah, now I understand why is it. Thanks! – ironsand Dec 20 '14 at 07:28