Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
In one of the Ruby koans, there's the following problem:
def test_slicing_arrays
array = [:peanut, :butter, :and, :jelly]
assert_equal _, array[0,1]
assert_equal _, array[0,2]
assert_equal _, array[2,2]
assert_equal _, array[2,20]
assert_equal _, array[4,0]
assert_equal _, array[4,100]
assert_equal _, array[5,0]
end
You must fill in the _ with the correct statement. The first four asserts work how I'd expect them to, but I'm confused about the last three.
array[4,0]
gives back []
, as does array[4,100]
. At this point I figured that ranges outside of the array (greater than 3 in this case) simply return an empty array.
But array[5,0]
returns nil
which has now confused me completely.
Can anyone explain this behaviour?