4

Given

array = [:a,:b,:c,:d] # with 4 elements:

array[3] => :d  # zero-based indices, I get that
array[4] => nil
array[5] => nil

array[3,0] => [] # OK since I asked for a slice with zero elements

Doco for array[start,length] says that it "Returns nil if the index (or starting index) are out of range."

array[5,0] => nil # OK
array[4,0] => []  # Hunh??

How come array[4,0] returns an array as opposed to nil?

[edit] Looks like this has already come up: see Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

To me the explanation looks a bit like hand waving, but I'll settle for it and just accept that ruby violates PLS here.

Community
  • 1
  • 1
Tom Porter
  • 49
  • 2
  • 1
    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-fro) – mu is too short Aug 11 '11 at 19:18

1 Answers1

1

I believe that the documentation does not word the behavior correctly. But intuitively, the bahavior makes sense. Just like it is possible to define a 0-element "sliver" at the beginning of the array, before all elements by indexing array[0,0], it should also be possible, symmetrically, to get a 0-element "sliver" at the end of the array, after all the elements, by indexing array[array.size,0]. Another example would be that it should intuitively always be possible to get a copy of an array by indexing over its whole range, i.e. array[0,array.size]; but this would not be possible for empty arrays if we returned nil when the starting index is equal to the array size.

user102008
  • 30,736
  • 10
  • 83
  • 104