Array Length Error in Programming Ruby 2nd Edition Page 49

Came across a minor oversight in a Ruby example on pg 49 of Programming Ruby. The test code checks that you can find a song in a list which is just wrapped into an array of song objects. It worked find until I used a negative test case to search for a song title that shouldn’t be in the list.

def testFindBySongTitle
    assert_equal(@song1, @song_list.with_title("Love Song"))
    assert_nil(@song_list.with_title("love song"))
  end

I got the familiar red bar and an error

1
Exception: undefined method 'name' for nil:NilClass

. So I stared at the code for a bit looking for something funky:

class SongList
  def with_title(title)
    for i in 0..@songs.length
      return @songs[i] if title == @songs[i].name
    end
    return nil 
  end
end

As it turned out I noticed it was actually iterating over the length of the array and since Ruby arrays are zero based indexes, I really needed to add the familiar

1
length -1

.

class SongList
  def with_title(title)
    for i in 0..@songs.length - 1
      return @songs[i] if title == @songs[i].name
    end
    return nil 
  end
end

So once again a negative test case came in handy. I went ahead and submitted it as possible errata.