Ruby koan - about arrays - test_accessing_array_elements array[5,0] [duplicate]
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>
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.
精彩评论