I'm working on the about_arrays.rb file within Ruby Koans and I noticed this piece of code and I'm not sure why the answer is what it is:
def test_slicing_arrays
array = [:peanut, :butter, :and, :jelly]
assert_equal [], array[4,0]
assert_equal [], array[4,100]
assert_equal nil, array[5,0]
end
Based on the output for Ruby Koans, can someone explain to me why array[4,0]
would evaluate to []
while array[5,0]
evaluates to nil?
. Why wouldn't array[5,0]
also evaluate to []
?
Out of curiosity, I tried array[6,0]
, array[7,0]
, and so on and also got nil. Is there something special that Ruby does for the array index next in line to get something appended to it?
EDIT:
I found "Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)", which asks the same question, but I'm still not understanding how indices work in array slicing.