2

Possible Duplicate:
Why does array.slice behave differently for (length, n)

In Ruby koan "about_arrays.rb", test_accessing_array_elements there's two similar start/length slice statements accessing parts of an array. Ref extract below. Both should be "out of range" yet one returns an empty array and the other returns nil. This matches possible results as per docs ruby doc. Why is it so?

irb(main):221:0> array = [:peanut, :butter, :and, :jelly]
=> [:peanut, :butter, :and, :jelly]
irb(main):222:0> array[4,0]
=> []
irb(main):223:0> array[5,0]
=> nil
irb(main):224:0>
irb(main):224:0> array[4]
=> nil
irb(main):225:0> array[5]
=> nil
irb(main):226:0>
Community
  • 1
  • 1
Straff
  • 5,499
  • 4
  • 33
  • 31
  • I came across this while running Ruby koans just this week and ended up in #ruby on irc to ask about it. The consensus of the room was "misfeature" or "bug by design", for what that's worth. (The behavior is documented in the docs for `Array#slice`, though the description of "special cases" isn't really encouraging.) – Telemachus Jul 21 '10 at 10:47
  • Chris is right, duplicate of [why-does-array-slice-behave-differently-for-length-n](http://stackoverflow.com/questions/3219229/why-does-array-slice-behave-differently-for-length-n) – Straff Jul 21 '10 at 09:10

1 Answers1

2

I think of it as some array methods referring to the gaps between elements, rather than the elements themselves, i.e. 0 is the space before the first element, 1 the space between the first and second element. Considered this way, the operation makes slightly more sense, as 4 is the gap after the fourth element, which is still within the array, so zero elements from this position is an empty array.

You can think of the insert method in the same way (although the documentation explicitly says otherwise).

However, this is probably a mental trick rather than an explanation - still, perhaps it will help someone.

Amanda
  • 86
  • 2