0

Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

Say you have an array

a = [1,2,3]

why the a.slice(3,6) returns [] while the a.slice(4,6) returns nil?

Community
  • 1
  • 1
Gerry
  • 5,326
  • 1
  • 23
  • 33

2 Answers2

4

The documentation lists special cases for when the start index equal to the length of the array:

a = [ "a", "b", "c", "d", "e" ]

# special cases
a[5, 1]                #=> []
a[5..10]               #=> []

from: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-slice

So this appears to be the built-in functionality, since the start index is the length of the array the slice method is supposed to return an [], but when you pass the length of the array you get nil. This is probably due to how Ruby is defining ranges within an array.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • Your answer is correct but this doesn't mean the same for the behaviour of `slice`. `slice` should literally slice (if we want to name it that way) the array, starting from the first_index and ending at the second_index, and thus returning nothing (which is `nil` in Ruby) in both cases. – Gerry Mar 29 '12 at 16:12
  • if an empty array was the same as nil, then the behavior above wouldn't have happened. – Hunter McMillen Mar 29 '12 at 16:43
  • Yes, it's built-in functionality, but the OP seemed to be asking "Why?" and the answer is: *to generalize assignment.* – DigitalRoss Mar 29 '12 at 17:40
2

Because it makes assignment more general

The mechanism is designed this way so slices can work in a highly generalized way on the left-hand side of assignment operators.

It doesn't really matter for #slice exactly because that result cannot be assigned but the same interpretation applies to x[3, 6] and those expressions can be assigned.

It's best to look at the array indices as identifying the spaces between elements, rather than the elements themselves.

This interpretation creates a consistent and useful interface ... for example, code can be written that will handle replacing elements or appending to zero length or populated Arrays, and all without needing special-case tests.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329