Okay, I’ve seen this question about the d*mn ruby koans posted several
places, but one aspect of fencepost slicing still eludes me.
In the following array:
array = [:peanut, :butter, :and, :jelly]
I get:
assert_equal [], array[4,0]
The “fence post” at the end of the array after :jelly exists and doesn’t
give a nil.
I don’t get why:
assert_equal [:jelly], array[4,-1]
Any pointers to clear this up?
Thanks and sorry if this has been asked 1000.times, I really did search!
Hi,
ary[start, length] → new_ary or nil
-
A negative length returns nil:
array = %i[peanut butter banana jelly]
p array[2, -1] #=>nil
-
A length of 0 can return a new array or nil:
p array[100, 0] #=> nil
p array[4, 0] #=>[]
To understand the last result, read the best post ever written on
slicing(although it is written for strings):
https://www.ruby-forum.com/topic/1393096#990065
My interpretation is that the index 4 is legal in two arg indexing,
and the length 0 is a legal length(i.e. it’s not negative), and
adding 0 to 4 does not go out of bounds, so nil is not the proper
return value.
But really, ruby could have been coded to return nil when you take a
slice of 0 length at the ending fencepost. You just have to accept:
That’s the way it is.