I got this question when doing ruby koans. Given this array:
array = [1, 2, 3, 4]
array[4, 0]
equals []
. However, array[5, 0]
equals nil
.
Both 4 and 5 are out of index. Why do they return different things?
I got this question when doing ruby koans. Given this array:
array = [1, 2, 3, 4]
array[4, 0]
equals []
. However, array[5, 0]
equals nil
.
Both 4 and 5 are out of index. Why do they return different things?
The first parameter of Array#slice(start,length) is the place between indices where slicing should begin :
array = [1, 2, 3, 4]
# elements : [ 1 2 3 4 ]
# ↑ ↑ ↑ ↑ ↑
# slice start indices : 0 1 2 3 4
slice(0,_)
begins left of 1
, slice(3,_)
begins left of 4
, and slice(4,_)
begins at the last possible place : right of 4
.
slice(4,0)
is still inside array
, it's the empty Array right of 4
.
slice(5,0)
isn't inside array
anymore, it's nil
.