I'm going through Ruby Koans as a way to learn Ruby. I'm having trouble understanding what the difference is between the two test cases in red, below, as to why the first is an empty array while the latter is nil. Seems to me like they should be the same (whichever result), as both having an offset beyond the last element of the array. Or is only one past the last element a special case?

  def test_slicing_arrays
    array = [:peanut, :butter, :and, :jelly]

assert_equal [:peanut], array[0,1]
assert_equal [:peanut, :butter], array[0,2]
assert_equal [:and, :jelly], array[2,2]
assert_equal [:and, :jelly], array[2,20]
[COLOR="#FF0000"]assert_equal [], array[4,0][/COLOR]
assert_equal [], array[4,100]
[COLOR="#FF0000"]assert_equal nil, array[5,0][/COLOR]
  end

Thanks.

    I always thought of it as starting at the nth comma for m more commas to understand. So think of it as having an implicit trailing comma, which you can then start at for 0 or more commas. Being that there are no more commas, you get an empty array. There is no 5th comma, explicit or implicit, to start at. This is not the "machine" way of reasoning, but its how I've simplified it to make sense when I've had to use Ruby.

    Or more visually:

    for array[0,1]
     | :peanut | :butter | :and | :jelly |
     ^_ start here
    
     | :peanut | :butter | :and | :jelly |
       ------> ^_ Move once and takes what's between
    
     | :peanut |
    
    
    for array[4,m]
     | :peanut | :butter | :and | :jelly |
                                         ^_ start here
    
     | :peanut | :butter | :and | :jelly |
                                    ---> ^_ Move m times, can't move stay here
    
     || (start and end are both |)
    
    
    
    for array[4+n, m]
     | :peanut | :butter | :and | :jelly |
                                          ^_ start here
    
     | :peanut | :butter | :and | :jelly |
                                     ---> ^_ Move m times, can't move stay here
    
      (Started out of bounds, never pointed at anything)
    

      So, long story short, it is essentially an edge case of sorts specific to being "just after" the last populated element, I guess. I think that I, for one, will try to avoid ever writing any code that depends on that -- and hopefully none that will ever break because I forgot about it. 🙂

        just remember to check for nil and empty array after slicing.

          Write a Reply...